2015-12-03 120 views
1

我有一個陣營組成部分,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); 
}, 

但是,如果我用componentWillReceivePropsstate.props會記得老props,而不是新的,我想。

我嘗試使用componentWillUpdate代替,但我不能設置裏面componentWillUpdate的狀態。

如何更改基於新道具的組件的狀態?

回答

3

componentWillReceiveProps hook傳遞新的道具作爲參數。

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

你需要傳遞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); 
},