What is the difference between componentWillMount and componentDidMount in ReactJS?

前端 未结 8 487
Happy的楠姐
Happy的楠姐 2020-11-29 20:05

I looked at Facebook\'s documentation at (React.Component) and it mentions how componentWillMount is invoked on the client/server whereas componentDidMou

8条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-29 20:43

    the constructor method is not the same as componentWillMount.

    According to the author of Redux, it is risky to dispatch actions from the constructor because it may result in mutating the state while rendering.

    However, dispatching from componentWillMount is just fine.

    from github issue:

    This happens when dispatch() inside one component's constructor causes a setState() inside another component. React keeps track of the “current owner” for such warnings—and it thinks we're calling setState() inside the constructor when technically constructor causes a setState() inside some other part of the application. I don't think we should handle this—it's just React trying its best do its job. The solution is, as you correctly noted, to dispatch() inside componentWillMount() instead.

提交回复
热议问题