【问题标题】:React props only update on render when re-renderingReact props 仅在重新渲染时更新渲染
【发布时间】:2016-12-30 11:36:16
【问题描述】:

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

比如下面的代码……

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

有谁知道为什么会发生这种情况并告诉我如何在渲染之前获取更新的道具?

【问题讨论】:

    标签: reactjs


    【解决方案1】:

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

    所以要获得新的道具,你需要这样做:

    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);
    }
    

    【讨论】:

      【解决方案2】:

      新的道具将在上述函数的参数中。

      例如componentWillReceiveProps(newProps)

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

      更新中:componentWillReceiveProps

      void componentWillReceiveProps(
        object nextProps
      )
      

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

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

      同样适用于其他方法。

      请检查docs for details

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-08-09
        • 1970-01-01
        • 2021-12-29
        • 1970-01-01
        • 1970-01-01
        • 2017-08-30
        • 2022-01-06
        • 2021-06-07
        相关资源
        最近更新 更多