如何在React生命周期中的渲染函数之前访问新的props.value

Kua*_*uan 3 lifecycle reactjs

所有:

如果我定义一个组件有一个名为"value"的属性,

var Child = React.createClass({
  componentWillReceiveProps: function(){
     console.log("componentWillReceiveProps",this.props.value);
  },
  shouldComponentUpdate : function(){
    console.log("shouldComponentUpdate", this.props.value);
    return true;
  },
  componentWillUpdate : function(){
    console.log("componentWillUpdate", this.props.value);
  },
  componentDidUpdate: function(){
    console.log("componentDidUpdate", this.props.value);
  },
  render: function(){
    return (
      <div>The value generated by Parent: {this.props.value}</div>
    );
  }
});
Run Code Online (Sandbox Code Playgroud)

如果我想将新设置的props.value赋予state.value(或者可能为转换/插值准备一个值),但渲染之前的所有阶段只有前一个值.谁能告诉我如何在渲染之前获得新值?

谢谢

Tom*_*tes 5

重要说明:componentWillReceiveProps已弃用:https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops


componentWillReceiveProps 在组件接收新道具时调用.

从这里,您可以使用setState而不触发渲染来更新组件的状态.

  1. 您可以从传递给 的第一个参数访问新的道具componentWillReceiveProps
  2. 你可以访问旧道具 this.props

从你的例子:

componentWillReceiveProps: function(nextProps){
    console.log("componentWillReceiveProps", nextProps.value, this.props.value);
},
Run Code Online (Sandbox Code Playgroud)

JSBin演示

  • 非常感谢.这解决了这个问题 (2认同)