prop在componentWillReceiveProps()方法中未定义

时间:2017-02-16 11:17:27

标签: react-native

我在Redux中使用ReactNative,并且我有一个reducer,它返回一个值数组。 我有以下组件应该接收reducer给出的数组。

我可以在mapStateToProps内部和render()内部成功打印整个数组,我可以看到这个数组的一部分。 问题是在componentWillReceiveProps()内部数组是未定义的。

class MyComponent extends Component {
      constructor(props) {
        super(props);
      }

      componentWillReceiveProps(){
        console.log("hey");  // I can see this in the terminal
        const { calculatedPercentages } = this.props;
        // here's the problem I get undefined 10 times
        for (let i=1; i<11; i++){
          console.log("test: "+calculatedPercentages[i]);
        }
        this.setState({myPercentages:calculatedPercentages})  
      }

      render() {    
        return (
          <View> 
          <Text>{this.props.calculatedPercentages[3]}</Text>  // this works and it prints out the correct value
          </View>
        );
      }


    const mapStateToProps = ({ myRed }) => {
      const { calculatedPercentages } = myRed;  
      // this loop works correctly, it shows me the 10 values I've inside the array
      for (let i=1; i<11; i++){
          console.log(calculatedPercentages[i]);
      }
      return { calculatedPercentages };
    };
}

1 个答案:

答案 0 :(得分:0)

componentWillReceiveProps方法作为第一个参数传递下一组道具,你需要像这样使用它:

componentWillReceiveProps (nextProps) {
  const { calculatedPercentages } = nextProps;

  for (let i=1; i<11; i++){
    console.log("test: "+calculatedPercentages[i]);
  }

  this.setState({myPercentages:calculatedPercentages})  
}

在您的原始代码中,您使用的是现有道具,因此您看不到更新。