在componentWillMount

时间:2017-10-02 02:32:25

标签: reactjs

在React组件的componentWillMount()方法中设置一些值是好还是坏?

说,我有一个链接到对象的受控组件。我通过道具收到一些值,需要在对象中设置它们。它看起来像这样:

class MyComponent extends Component {

   constructor(props) {
      super(props);
   }

   componentWillMount() {

       // I receive "color" through props and need to set it
       // in my object which is done through an action
       this.props.actions.setColor(this.props.color);
   }

   render() {
      return(
         <div>
             // Some stuff here
         </div>
      );
   }
}

尝试确定设置此值的最佳时间/地点。最终,我需要myObject中的值并通过道具接收值。

尝试查看是否在componentWillMount()中处理此问题是个好主意。

1 个答案:

答案 0 :(得分:0)

如果电话有副作用,例如更新商店,这是一个坏主意。来自componentWillMount的文档:

  在安装发生之前立即调用

componentWillMount()。它在render()之前调用,因此在此方法中同步设置状态不会触发重新呈现。 避免在此方法中引入任何副作用或订阅。

componentWillMount也可以多次调用,例如服务器端渲染。您应该使用componentDidMount代替。

另一方面,如果调用没有副作用,您应该将调用移到构造函数中。

相关问题