What is the difference between componentWillMount and componentDidMount in ReactJS?

前端 未结 8 489
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:48

    componentWillMount is essentially the constructor. You can set instance properties that don't affect render, pull data from a store synchronously and setState with it, and other simple side effect free code you need to run when setting up your component.

    It's rarely needed, and not at all with ES6 classes.

    0 讨论(0)
  • 2020-11-29 20:49

    componentWillMount is done before the INITIAL render of a component, and is used to assess props and do any extra logic based upon them (usually to also update state), and as such can be performed on the server in order to get the first server side rendered markup.

    componentDidMount is performed AFTER the initial render when the DOM has been updated (but crucially BEFORE this DOM update is painted to the browser, allowing you to do all kinds of advanced interactions with the DOM itself). This of course can only happen in the browser itself and so does not occur as part of SSR, as the server can only generate markup and not the DOM itself, this is done after it gets sent to the browser if using SSR

    Advanced interactions with the DOM you say? Whaaaat??... Yep - at this point because the DOM has been updated (but the user has not seen the update in browser yet) it is possible to intercept actual painting to the screen by using window.requestAnimationFrame and then do things like measure the actual DOM elements that will be output, to which you can perform further state changes, super useful for example animating to a height of an element that has unknown variable length contents (as you can now measure the contents and assign a height to the animation), or to avoid flash of content scenarios during some state change.

    Be very careful though to guard state changes in any componentDid... as otherwise can cause an infinite loop because a state change will also cause a re-render, and hence another componentDid... and on and on and on

    0 讨论(0)
提交回复
热议问题