What is the purpose of having functions like componentWillMount in React.js?

前端 未结 5 871
一个人的身影
一个人的身影 2021-02-04 00:32

I have been writing components in React.js recently. I have never had to use methods like componentWillMount and componentDidMount.

rend

5条回答
  •  爱一瞬间的悲伤
    2021-02-04 01:24

    Why React Life Cycle Methods?

    Intend to use third-party (Ex D3.js) library with React Component


    class Example extends React.component{
      constructor(){
        // init state
        // will be called only once
      }  
      componentWillMount(){
        // will be called only once
        // will not be triggered when re-rendering
        // usually will fetch data that is needed in order 
        // to render properly from other API
      }
      shouldComponentUpdate(){
          return false
          // will not re-render itself after componentDidMount(){}
      }
      render(){
        return (
          
    ) } componentDidMount(){ d3.select(".chart") .selectAll("p") // d3.js ........ // d3.js ........ // Usually, this will trigger React to re-render itself, // but this time will not because we have set // shouldComponentUpdate to false } }

    Why React wants to do this?

    Since rendering DOM is an expensive operation, React uses the layer of virtual DOM to update only DOM / DOMs that is/are different from previous state.

提交回复
热议问题