我有一个React组件AttributeSingleChoice
,我这样调用它:
根据我在其中接收到的新props
,我想更改它的状态,如下所示:
componentWillReceiveProps: function() {
var attributeTypes = this.selectAttributes();
this.setState({
singleChoiceAttributes: attributeTypes});
},
selectAttributes: function() {
return this.props.classification.attributes.map(function (elem) {
if(elem.attributeType == "A") {
return {description: elem.description, name: elem.name}
}
}).filter(Boolean);
},
然而,如果我使用componentWillReceiveProps
,state.props
将记住旧的props
,而不是我想要的新的。
我尝试使用componentWillUpdate
,但无法在componentWillUpdate
中设置状态。
如何根据新道具更改组件的状态?
componentWillReceiveProps
钩子将作为参数传递新的props。
componentWillReceiveProps: function(newProps) {
newProps !== this.props
}
您可以在selectAttributes
函数上接受带有参数的备用道具。
selectAttributes: function(props) {
// fallback to regular props if nothing passed
props = props || this.props;
return props.classification.attributes.map(function (elem) {
// ...
}).filter(Boolean);
}
然后在新道具可用时传递。
componentWillReceiveProps: function(newProps) {
var attributeTypes = this.selectAttributes(newProps);
this.setState({
singleChoiceAttributes: attributeTypes
});
}
您的componentwilleriveprops标头不正确。您应该为nextOps输入一个参数,该参数将包含传入的道具。然后根据nextOps设置状态变量。http://facebook.github.io/react/docs/component-specs.html#updating-组件将接收道具
您需要将nextProps
传递到您的函数:
componentWillReceiveProps: function( nextProps ) {
var attributeTypes = this.selectAttributes( nextProps );
this.setState({
singleChoiceAttributes: attributeTypes});
},
selectAttributes: function( nextProps ) {
var props = nextProps || this.props;
return props.classification.attributes.map(function (elem) {
if(elem.attributeType == "A") {
return {description: elem.description, name: elem.name}
}
}).filter(Boolean);
},