react state初始化问题

报错信息

Can't call setState on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the *** component.

大致:

不能再一个组件尚未mounted时调用 setState() 方法,这是一个空操作,但是可能会导致bug,所以, 直接给this.state 赋值,或者定义成state = {};

问题代码

import React from 'react';

import { Icon } from 'antd';

class ProjMain extends React.Component {

  constructor(props) {

    super(props);

    this.setState({

      docDetail: {}

    })

  }



  render() {

    return (

        

{this.state.docDetail))}

); } } export default ProjMain;

render() 方法中如果使用了 this.state.docDetail,会导致编译报错

1538031794.png

仔细检查代码


constructor(props) {

    super(props);

    this.setState({

      docDetail: {}

    })

  }

constructor 里使用了 setState,改为直接赋值后正常

你可能感兴趣的:(react state初始化问题)