【问题标题】:set initial react component state in constructor or componentWillMount?在构造函数或 componentWillMount 中设置初始反应组件状态?
【发布时间】:2016-10-13 10:31:03
【问题描述】:

在 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});
  }
}

【问题讨论】:

标签: reactjs


【解决方案1】:

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

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

此外,如果您有可用的类属性(babel 阶段 1),那么您可以执行以下操作:

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

  render() {
    ....
  }
}

【讨论】:

  • 因为我记得读过从不直接改变 this.state :facebook.github.io/react/docs/component-api.html#setstate
  • 对不起,要清楚,设置初始状态时不要使用它。 :) 其他地方都可以。
  • 这种情况下为什么没问题?
  • 还有为什么使用构造函数比使用componentWillMount更好?
  • React 团队直接建议在使用 ES6 类时在构造函数中设置状态。 Read about that here。我假设有一些我们不知道的内部结构需要在任何生命周期事件被触发之前设置初始状态。
猜你喜欢
  • 1970-01-01
  • 2017-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-04
  • 2020-06-30
  • 2011-05-21
相关资源
最近更新 更多