Javascript 反应-改变道具时的状态
我有一个React组件,Javascript 反应-改变道具时的状态,javascript,reactjs,Javascript,Reactjs,我有一个React组件,AttributeSingleChoice,我这样调用它: componentWillReceiveProps: function() { var attributeTypes = this.selectAttributes(); this.setState({ singleChoiceAttributes: attributeTypes}); }, selectAttributes: function() { return th
AttributeSingleChoice
,我这样调用它:
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: 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);
},
但是,如果我使用组件将接收道具
,状态。道具
将记住旧的道具
,而不是我想要的新道具
我尝试改用componentWillUpdate
,但无法在componentWillUpdate
中设置状态
如何根据新道具更改组件的状态?将新道具作为参数传递
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
});
}
您需要将
nextrops
传递到您的函数:
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);
},
您的组件WillReceiveProps标题不正确。您应该为nextProps引入一个参数,该参数将包含传入的道具。然后,根据nextProps设置状态变量