React.js, change event listener for a specific proposal?

I want to call a function when this.props.mapinstalled in a React component defined using ES6 class syntax:

export default class MapForm extends React.Component {...

I am currently using componentDidUpdate()it because it fires when installed props, but it also fires from other unrelated events that are not ideal.

On the other hand, componentWillReceiveProps()happens at an early stage in the life cycle of the component that seems ( this.props.mapreturns undefinedat this point)

So, I want to call the function only when installed this.props.map.

Do I have a hook? Or maybe a specific pattern?

+4
source share
1 answer

if you only want to run it once . You can do it

componentDidUpdate(pProps){
    if(!pProps.map && this.props.map){
        this.props.callSomeFunc();
    }
}

or you can use the function before rendering

componentWillRecieveProps(nProps){
    if(!this.props.map && nProps.map){
        this.props.callSomeFunc();
    }
}

if you want to know when it will change in order to call a function (this means that it has already been created, but changed to something else)

if( (!pProps.map && this.props.map) || (this.props.map !== pProps.map){

(if this is the object you want to change, this is the second comparison with the deep)

Both of these functions have the concept of the next or previous state of a component before and after its update.

componentDidUpdatemeans that the render is completed and the component is updated. It has two arguments that you can include in the function (prevProps, prevState), where are the previous details and the state of the component before updating it.

alternatively componentWillReceivePropshas the opposite side(nextProps, nextState)

, , ​​(aka one undefined, )


EDIT:

, , (nProps) .

count = 1;
<SomeComponent count={count} />

SomeComponent

class SomeComponent extends React.Component {

    componentWillReceiveProps(nProps){
        console.log(this.props.count); // logs 0
        console.log(nProps.count);  // logs 1
    }
}
SomeComponent.defaultProps = {count: 0};

, 5 .

componentWillReceiveProps(nProps){
    console.log(this.props.count); // logs 1
    console.log(nProps.count);  // logs 6
}

, . this.props.count - . nextProps.count(nProps.count) - , . , , !:)

+3

All Articles