React Learning (6)--On the component life cycle issues

Source: Internet
Author: User


During the development of the project, a problem was encountered:



The parent component requests background data and, when received, passes the data props to the child components, which display different content depending on the data received, while the subcomponent itself can change the contents of the parent component's data according to the click operation.



Therefore, after the child component receives the props value of the parent component, because the props value cannot be modified, the child component needs to put the props value in state, and the child component changes it according to its click operation, which changes the contents of the component display.



The value passed by the parent component is not available in Componentdidmount and can be obtained in render. However, if the portion of the fetch value is written in render, it causes each page update to take a value from the parent component, and the sub-component's Click action modifier value does not work.



The sub-component code is as follows:


 
class child extends PureComponent { static propTypes = {
        value: PropTypes.bool.isRequired
    };
    constructor(props) {
        super( props); this.state = {
            value: false };
    }
    changeValue = () => { this.setState({
            value: false });
    }
    render() { this.state = {
            value: this.props.value
        }; return ( <div  style={{ display: value ? 'block':'none' }}>
               <img src={src} alt="" />
               <div className={styles.value}>这是父组件的传值:{value}</div>
               <div className={styles['icon-close']} onClick={this.changeValue}>
                   <img src={close} alt="" />
               </div>
            </div> );
    }
}
export default Child;




Workaround 1: Write the Click's Close method in render


But the notation is not very canonical, and the render () function should be purely, meaning that the function does not modify the component state, each call returns the same result, does not read and write the DOM information, and does not interact with the browser (for example, by using setTimeout).


 
 
class child extends PureComponent { static propTypes = {
        value: PropTypes.bool.isRequired
    };
    constructor(props) {
        super( props); this.state = {
            value: false };
    }
    render() { this.state = {
            value: this.props.value
        };  changeValue = () => {
            this.setState({
                value: false
            });
        } return ( <div  style={{ display: value ? 'block':'none' }}>
               <img src={src} alt="" />
               <div className={styles.value}>这是父组件的传值:{value}</div>
               <div className={styles['icon-close']} onClick={changeValue}>
                   <img src={close} alt="" />
               </div>
            </div> );
    }
}
export default Child;

Solution 2: Use Componentwillreceiveprops
 
class child extends PureComponent { static propTypes = {
        value: PropTypes.bool.isRequired
    };
    constructor(props) {
        super( props); this.state = {
            value: false };
    }  componentWillReceiveProps(nextProps) { this.setState({
            value: nextProps.value
        });
    }  changeValue = () => { this.setState({
            value: false });
    }
    render() { return ( <div  style={{ display: value ? 'block':'none' }}>
               <img src={src} alt="" />
               <div className={styles.value}>这是父组件的传值:{value}</div>
               <div className={styles['icon-close']} onClick={this.changeValue}>
                   <img src={close} alt="" />
               </div>
            </div> );
    }
}
export default Child;
Summary: The life cycle of react components
    • Componentwillmount
    • Componentdidmount
    • Componentwillreceiveprops
    • shouldcomponentupdate
    • Componentwillupdate
    • componentdidupdate
    • Componentwillunmount
1. ComponentwillmountComponent will be mounted


Component has just gone through constructor, initial data



Called immediately before initialization of the render execution, both the server side and the client are called only once



The component has not yet entered render, the component has not been rendered, the DOM has not yet been rendered



If you call Setstate,render () within this method, you will perceive the updated state, which will be executed only once, although the state has changed.


2. Componentdidmount Component Rendering complete


Called immediately after initialization of the render execution, only valid for the client (the server side is not called)



Now that the DOM node has been generated, the AJAX request can be called here, and the component will be re-rendered after the data setstate is returned.



At this point in the life cycle, the component has a DOM representation, and you can get the corresponding DOM node by This.getdomnode ()



You can call settimeout, setinterval, or send Ajax requests in this method (to prevent asynchronous operations from blocking the UI)


3.componentWillReceiveProps (Nextprops)


Called when the component receives a new prop (updated). This method is not called when the render is initialized.



More props required to re-render the component after accepting a parent component change



This function can be used as an opportunity for the react to update the state before the render () renders after the prop is passed in.



Calling This.setstate () in this function will not cause a second render.


Re-render the component by comparing the Nextprops SetState to the state of the current component by contrasting nextprops and this.props

 
class child extends PureComponent { static propTypes = {
        value: PropTypes.bool.isRequired
    };
    constructor(props) {
        super( props); this.state = {
            value: false };
    }  componentWillReceiveProps(nextProps) { this.setState({
            value: nextProps.value
        });
    }  changeValue = () => { this.setState({
            value: false });
    }
    render() { return ( <div  style={{ display: value ? 'block':'none' }}>
               <img src={src} alt="" />
               <div className={styles.value}>这是父组件的传值:{value}</div>
               <div className={styles['icon-close']} onClick={this.changeValue}>
                   <img src={close} alt="" />
               </div>
            </div> );
    }
}
export default Child;
4. Shouldcomponentupdate (nextprops,nextstate)


Unique life cycle for controlling component re-rendering



Since the state changes after setstate in react, the component will enter the process of re-rendering (for the time being, in fact, some things will not be re-rendered after setstate, such as the array reference does not change). React the re-rendering of the parent component will cause all of its subcomponents to be re-rendered, and at this point we do not need all the subcomponents to be re-rendered, so we need to make a judgment in the child component's life cycle. return false here to prevent updates to the component



If Shouldcomponentupdate returns FALSE, Render () will not execute until the next state changes. (in addition, componentwillupdate and componentdidupdate are not called.) )



Called before a new props or state is received and will be rendered. This method is not invoked when initializing the render, nor when using the ForceUpdate method.



By default, Shouldcomponentupdate always returns true to avoid minor bugs when state changes, but if state is always carefully treated as immutable, only the values from props and state are read in render (). At this point you can override the Shouldcomponentupdate method to implement the alignment logic of the new old props and state.



If performance is a bottleneck, especially when there are dozens of or even hundreds of components, using shouldcomponentupdate can improve the performance of your application.


5. Componentwillupdate (nextprops,nextstate)


Called when the component receives a new props or state but has not yet been render. Will not be called at initialization time.



Shouldcomponentupdate returns True, the component enters the re-rendered process and enters componentwillupdate, where it can also get nextprops and nextstate



You cannot use This.setstate () in this method. If you need to update state to respond to a change in a prop, you can use Componentwillreceiveprops.


6. Componentdidupdate (prevprops,prevstate)


Called immediately after the component has finished updating. Will not be called at initialization time.



After the component has been updated, react will enter Componentdidmount only after the first initialization succeeds, and then each time it is re-rendered, it will enter the lifecycle.



is called immediately after the component's update has been synchronized to the DOM.



Here you can get prevprops and prevstate, the props and state before the update.



Use this method to manipulate DOM elements after a component update.



The V0.9,dom node is passed in as the last parameter for compatibility. If you use this method, you can still use This.getdomnode () to access the DOM node.


7.componentWillUnmount ()


Called immediately when the component is removed from the DOM.



Perform any necessary cleanup in the method, such as an invalid timer, or clear the DOM element created in Componentdidmount, removing the listener RemoveEventListener in all builds


In addition, 8.constructor


The constructor parameter accepts two parameter props,context, which can get the props,context passed down to the parent component,



If you want to use props or context inside the constructor constructor, you need to pass in and pass in the Super object.


As long as the component exists constructor, it is necessary to write super, otherwise this point will be error 9. Render function


The render function inserts the JSX generated DOM structure, and react generates a copy of the virtual DOM tree,



At each component update, this react compares the old and new Dom trees before and after the update with their diff algorithm, and later finds the smallest, differentiated DOM node and re-renders



The render function in React16 allows you to return an array, a single string, etc., without limiting it to a top-level DOM node, which can reduce a lot of unnecessary div


The sequence of execution of the component life cycle:


In the react component mount and render process, the bottommost sub-component is the first to complete the mount and update.



Constructor () constructor, Componentwillmount execution Order: Sub-components, sub-components, child component, top-level parent component



Render, Componentdidmount Order: Sub-component, child component, sub-component, bottom sub-components, and top-level parent component



Here is an example of the http://www.runoob.com rookie tutorial:


 
class Button extends React.Component {
  constructor(props) {
      super(props); this.state = {data: 0}; this.setNewNumber = this.setNewNumber.bind(this);
  }
  
  setNewNumber() { this.setState({data: this.state.data + 1})
  }
  render() { return ( <div>
            <button onClick = {this.setNewNumber}>INCREMENT</button>
            <Content myNumber = {this.state.data}></Content>
         </div> );
    }
} class Content extends React.Component {
  componentWillMount() {
      console.log('Component WILL MOUNT!')
  }
  componentDidMount() {
       console.log('Component DID MOUNT!')
  }
  componentWillReceiveProps(newProps) {
        console.log('Component WILL RECEIVE PROPS!')
  }
  shouldComponentUpdate(newProps, newState) { return true;
  }
  componentWillUpdate(nextProps, nextState) {
        console.log('Component WILL UPDATE!');
  }
  componentDidUpdate(prevProps, prevState) {
        console.log('Component DID UPDATE!')
  }
  componentWillUnmount() {
         console.log('Component WILL UNMOUNT!')
  }
 
    render() { return ( <div>
          <h3>{this.props.myNumber}</h3>
        </div> );
    }
}
ReactDOM.render( <div>
      <Button />
   </div>,
  document.getElementById('example')
);

Operation Result:

(Console info)


Click the button:



Reference: WWW.JIANSHU.COM/P/C9BC994933D5



www.jianshu.com/p/ee122bb5b14b


Http://www.runoob.com/react/react-component-life-cycle.html


50942808


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.