Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 组件将接收在react中呈现两次的道具_Javascript_Reactjs - Fatal编程技术网

Javascript 组件将接收在react中呈现两次的道具

Javascript 组件将接收在react中呈现两次的道具,javascript,reactjs,Javascript,Reactjs,我正在开发react js,我有一个子组件,它是这样写的 constructor(props) { super(props); this.state = { volume: this.props.forcasted_volume, yearValue:Number(localStorage.getItem('year'))//it's 2017 value loading: false }; } componentWillRece

我正在开发react js,我有一个子组件,它是这样写的

 constructor(props) {
    super(props);
    this.state = {
      volume: this.props.forcasted_volume,
     yearValue:Number(localStorage.getItem('year'))//it's 2017 value
      loading: false
    };
  }
 componentWillReceiveProps(nextProps) {
    console.log(
      'before if condition...',
      this.state.yearValue,
      Number(localStorage.getItem('plan_year'))
    );
    if (
      this.state.yearValue ==
      localStorage.getItem('plan_year')
    ) {
      console.log('inside if condition.....', nextProps);
      this.state = {

        volume: nextProps.forcasted_volume,

        loading: false
      };
    } else this.setState({ loading: false });
  }

现在我的问题是,我第一次看到我的
组件将收到两次调用我的
this.state.yearValue
是我预期的2017年,但第二次它显示了
未定义的
我不明白两件事为什么它调用了两次?我能控制它吗?为什么第二次它的值变成了
未定义的

道具与当前类无关。这是父类/订阅还原器的属性。检查是否使用某些
setState
或其他方式第二次重新呈现父对象。

您使用的是
this.state=…
而不是setState。Setstate仅更改所提供属性的值,其中“this.state=”更改整个集合。您应该使用
setState
,因为这也会影响重新渲染

在if中。。。语句,将this.state更新为
这个.setState({volume:nextrops.forcasted_volume,loading:false}),就像您在else语句中所做的那样。

componentWillReceiveProps将在每个父级渲染中调用。因此,可能是由于某种原因,在父级中更新了道具,或者您对道具进行了变异,但为什么我的
yearValue
第二次未定义?这就是为什么yearValue第二次未定义?这是完全正确的。全局重写状态会将yearValue的值保留为undefined。Vihang,是的,这是正确的,因为最初是在构造函数中设置的,但后来在第一次调用componentwillreceiveprops时将其清除。