当重新渲染时,React道具只在渲染时更新

问题描述:

当我尝试使用不同的道具与初始渲染进行比较来重新渲染反应组件时,我只能在调用渲染时看到更新的道具值。所有以前的生命周期方法都会返回旧的prop值。当重新渲染时,React道具只在渲染时更新

例如,下面的代码...

componentWillReceiveProps() { 
    console.log("componentWillReceiveProps"); 
    console.log(this.props.calls); 
} 

shouldComponentUpdate() { 
    console.log("shouldComponentUpdate"); 
    console.log(this.props.calls); 
    return true; 
} 

componentWillUpdate() { 
    console.log("componentWillUpdate"); 
    console.log(this.props.calls); 
} 

componentDidUpdate() { 
    console.log("componentDidUpdate"); 
    console.log(this.props.calls); 
} 

render() { 
    console.log("render"); 
    console.log(this.props.calls); 
} 

当新道具将返回重新描绘......

componentWillReceiveProps 
oldProp 
shouldComponentUpdate 
oldProp 
componentWillUpdate 
oldProp 
render 
newProp 
componentDidUpdate 
newProp 

有谁知道为什么发生这种情况,并建议我如何能得到渲染之前更新的道具?

Life Cycle方法是更新过程(componentWillReceivePropsshouldComponentUpdatecomponentWillUpdate)更新的实际道具之前发生的一部分。为了获得新的道具,例如检查组件是否应该在shouldComponentUpdate中更新,反应将新道具作为参数传递给方法。

因此,要获得新的道具,你需要这样做:

componentWillReceiveProps(nextProps) { 
    console.log("componentWillReceiveProps"); 
    console.log(nextProps.calls); 
} 

shouldComponentUpdate(nextProps) { 
    console.log("shouldComponentUpdate"); 
    console.log(nextProps.calls); 
    return true; 
} 

componentWillUpdate(nextProps) { 
    console.log("componentWillUpdate"); 
    console.log(nextProps.calls); 
} 

componentDidUpdate() { 
    console.log("componentDidUpdate"); 
    console.log(this.props.calls); 
} 

render() { 
    console.log("render"); 
    console.log(this.props.calls); 
} 

新的道具将在提到的功能的参数。

E.g. componentWillReceiveProps(newProps)

  • this.props是老道具
  • newProps是新的道具。

更新:componentWillReceiveProps

void componentWillReceiveProps(
    object nextProps 
) 

当组件接收新道具时调用。此方法不用于初始渲染。

使用this作为在使用this.setState()更新状态来调用render()之前对prop过渡作出反应的机会。旧的道具可以通过this.props访问。在这个函数中调用this.setState()不会触发额外的渲染。

其他方法也是如此。

请检查docs for details