构造函数与componentWillMount; componentWillMount可以做什么,构造函数不能?

Yad*_*ran 37 javascript constructor class ecmascript-6 reactjs

据我所见,唯一componentWillMount可以做的constructor就是打电话setState.

componentWillMount() {
    setState({ isLoaded: false });
}
Run Code Online (Sandbox Code Playgroud)

由于我们尚未调用render,因此setStatecomponentWillMount进入render()第一遍之前,in 将准备状态对象.这与a基本相同constructor:

constructor(props) {
    super(props);
    this.state = { isLoaded: false };
}
Run Code Online (Sandbox Code Playgroud)

但我看到另一个componentWillMount有用的用例(在服务器端).

让我们考虑异步的东西:

componentWillMount() {
    myAsyncMethod(params, (result) => {
        this.setState({ data: result });
    })
}
Run Code Online (Sandbox Code Playgroud)

这里我们不能使用constructoras赋值来this.state触发render().

怎么样setStatecomponentWillMount?根据React文档:

componentWillMount()在安装发生之前立即调用.之前调用它render(,因此在此方法中设置状态不会触发重新渲染.避免在此方法中引入任何副作用或订阅.

所以,在这里我认为React将使用新的状态值进行第一次渲染并避免重新渲染.

问题1:这是否意味着,componentWillMount如果我们调用setState异步方法的回调(可以是一个promise回调),React会阻止初始渲染,直到执行回调为止?

客户端进行此设置(是的,我在服务器端呈现中看到了这个用例),如果我认为上面的情况属实,那么在异步方法完成之前我不会看到任何内容.

我错过了任何概念吗?

问题2:我可以componentWillMount使用但不使用constructor和的任何其他用例componentDidMount吗?

Lyu*_*mir 17

这是否意味着,在componentWillMount中,如果我们在异步方法的回调中调用setState(可以是一个promise回调),React会阻止初始渲染,直到执行回调为止?

不,看到 这里.

以下代码不会阻止渲染(请记住,这将是一个反模式,无论如何调用setState)

componentWillMount: function() {
     new Promise((resolve, reject) => {
        setTimeout(()=> {
            resolve();
        }, 2000)
     }).then(() => this.setState({ promiseResult: 'World' }));
  },
Run Code Online (Sandbox Code Playgroud)

问题2:我是否可以使用componentWillMount实现任何其他用例,但不使用构造函数和componentDidMount?

不,对于ES6课程,您可以丢弃componentWillMount.只有在您使用时才需要它React.createClass({... })

编辑:显然,我错了.感谢@ Swapnil指出这一点.这是讨论.

如果constructor在另一个组件中修改状态存在副作用,则React会发出警告,因为它假定setStateconstructor自身中并且可能在render()被调用期间.所以没有副作用constructor.

如果你这样做不是这种情况componentWillMount,不会抛出任何错误.另一方面,来自facebook的人也不鼓励副作用componentWillMount.因此,如果您没有任何副作用,您可以使用constructor而不是componentWillMount.对于副作用,建议使用componentDidMount而不是componentWillMount.无论哪种方式,你都不需要componentWillMount.

  • 对于ES6,如果我使用Redux并希望在初始加载时调度操作,建议在componentWillMount而不是构造函数中调度操作.[它说在这里](https://github.com/reactjs/react-redux/issues/129) (4认同)