reactjs-在构造函数或componentWillMount中设置初始React组件状态?

在React组件中,最好是在Constructor()或componentWillMount()中设置初始状态?

export default class MyComponent extends React.Component{
  constructor(props){
    super(props);
    this.setState({key: value});
  }
}

要么

export default class MyComponent extends React.Component{
  componentWillMount(props){
    this.setState({key: value});
  }
}
freedrull asked 2020-02-22T01:16:30Z
1个解决方案
68 votes

在使用ES6类时,最好在构造函数中使用,但不要使用setState API,而是这样做:

export default class MyComponent extends React.Component{
  constructor(props){
    super(props);
    this.state = { key: value };
  }
}

另外,如果您有可用的类属性(Bab期1),则可以执行以下操作:

export default class MyComponent extends React.Component{
  state = { key: value };

  render() {
    ....
  }
}
ctrlplusb answered 2020-02-22T01:16:48Z
translate from https://stackoverflow.com:/questions/37782403/set-initial-react-component-state-in-constructor-or-componentwillmount