React.js,事件监听器onChange for Specific Prop?

mal*_*ers 6 javascript reactjs

我想this.props.map在React组件上设置时触发一个函数- 使用ES6类语法定义:

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

目前,我正在使用componentDidUpdate()它,因为它在props设置时被触发- 但它也是由其他不相关的事件触发,这是不理想的.

另一方面,componentWillReceiveProps()在组件的生命周期的早期发生(在此时this.props.map返回undefined)

所以我想this.props.map设置时触发一个函数.

我错过了一个钩子吗?或者某种模式?

Joh*_*ell 5

如果你只想触发一次。你可以这样做

componentDidUpdate(pProps){
    if(!pProps.map && this.props.map){
        this.props.callSomeFunc();
    }
}
Run Code Online (Sandbox Code Playgroud)

或者你可以使用 before render 函数

componentWillRecieveProps(nProps){
    if(!this.props.map && nProps.map){
        this.props.callSomeFunc();
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您想知道它何时更改以调用该函数(意味着它已经创建但已更改为其他内容)

if( (!pProps.map && this.props.map) || (this.props.map !== pProps.map){
Run Code Online (Sandbox Code Playgroud)

(如果它是一个对象,您可能需要将第二个比较更改为深层比较)

这两个函数都具有组件更新之前和之后的下一个或上一个状态的概念。

componentDidUpdate表示渲染已完成并且组件已更新。它有两个参数,您可以将其包含在函数中(prevProps, prevState),其中它们是组件更新之前的先前属性和状态。

或者componentWillReceiveProps有相反的一面(nextProps, nextState)

通过这两者,我们可以比较组件的前一个 props 或下一个 props,并查看该转换是否是在设置地图时发生的(即一个未定义,另一个未定义)


编辑:

可视化正在发生的事情,这样你就知道下一个道具是什么(nProps),看看这个。

count = 1;
<SomeComponent count={count} />
Run Code Online (Sandbox Code Playgroud)

现在在 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};
Run Code Online (Sandbox Code Playgroud)

现在假设我们加 5 来计数。

componentWillReceiveProps(nProps){
    console.log(this.props.count); // logs 1
    console.log(nProps.count);  // logs 6
}
Run Code Online (Sandbox Code Playgroud)

基本上它会在您实际使用新道具渲染之前执行。this.props.count 是组件中的当前值。nextProps.count (nProps.count) 是下一个传入的值。希望有助于解释它是如何工作的!:)