所有:
如果我定义一个组件有一个名为“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>
);
}
});
如果我想将新设置的props.value赋予state.value(或者可能为转换/插值准备一个值),但渲染之前的所有阶段只有前一个值。谁能告诉我如何在渲染之前获得新值?
谢谢
重要说明:componentWillReceiveProps
已被弃用:https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops
当组件接收新道具时,会调用componentWillReceiveProps
。
从这里,您可以使用setState
更新组件的状态,而不会触发渲染。
componentWillReceiveProps
的第一个参数访问新的道具this.props
从你的例子:
componentWillReceiveProps: function(nextProps){
console.log("componentWillReceiveProps", nextProps.value, this.props.value);
},
对于任何通过谷歌发现这个老问题的人来说,它已经过时了。 You shouldn't be using this function anymore,此外,还有其他解决方案不涉及更新状态!看一下这个react.js博客文章You Probably Don't Need Derived State。
目前还不完全清楚OP想要做什么,但该文章中有各种适当的解决方案。在我的例子中,当我点击一个不同的元素时,我想重置一个弹出窗口。你可以用the key attribute做到这一点。它就像魔法一样。 :)