What is a componentWillReceiveProps?

ComponentWillReceiveProps is a part in the React life cycle, the React of life cycle, the students can learn more about here.

ComponentWillReceiveProps when initializing render will not perform, it will be accepted in the Component to the new state (Props) is triggered, commonly used in the parent Component state update subcomponents of rendering. This thing is very useful, but once used incorrectly can cause very serious consequences.

In componentWillReceiveProps the callback function, we can get to is the props, through this. Props to get, then the new props is through the function of the incoming parameters, Here we can compare the two props to make a secure change to the state of this component and then either re-render our component or trigger some method in a child component.

// This is a good way to interact with a parent component. Usually, the parent component needs to control the rendering or destruction of the child component through some state...

componentWillReceiveProps(nextProps) {The first parameter in the / / componentWillReceiveProps method of representing the incoming new Props
    if (this.props.sharecard_show ! == nextProps.sharecard_show){// Here we can still get the old external state using this.props
        // Compare the old and new states to determine whether to proceed with other methods
        if (nextProps.sharecard_show){
            this.handleGetCard(); }}}Copy the code

ComponentWillReceiveProps commonly used way is above, but if the improper use may lead to the following consequences, generally embodied in the component into a render loop, he will accept the new external state, leading to itself has been rendered.

componentWillReceiveProps(nextProps) {
    if (this.props.sharecard_show ! == nextProps.sharecard_show){if (nextProps.sharecard_show){
            this.handleGetCard();
        }
    }
}

handleGetCard() {
    this.props.test()
}

// Inside the parent component

test() {
    this.setState({
        sharecard_show:!this.state.sharecard_show
    })
}
Copy the code

Once such code is present in a project, there is a high chance that it will get stuck in an infinite loop, where the two components will always pass state and rerender, and the page will probably hang. This is the place where one of the need to pay attention to, in addition we need to keep in mind, want to make any changes in the componentWillReceiveProps will best compares two status, if the state has a different just execute the next step. Otherwise, it’s easy to render the component multiple times, and those renderings are meaningless.