简体   繁体   English

向现有状态添加新值-React Native

[英]Add new values to existing state - React Native

this.setState ({
      information: [{
                   country: 'country1',
                   place: 'place1'
                   }]
});

This setState(); 这个setState(); executes a multiple time in a for each loop. 为每个循环执行多次。 The problem is that the existing value will be overwritten every loop. 问题在于现有值将在每个循环中被覆盖。 What I have to change to 'add' the new values every loop? 我必须更改以在每个循环中“添加”新值吗?

UPDATE: I figured out a working solution for my problem below: 更新:我为下面的问题找到了一个可行的解决方案:

this.setState (state => ({
                    countries: [...state.countries,
                        {
                            name: child.key.toString(),
                            uri: snapshot.val().toString()
                        }
                    ]
                }));

You can do it this way: 您可以这样操作:

        this.setState(state=> ({
            information: {
              country: [...state.information.country, "country1"],
              place:   [...state.information.place, "place1"]
            }
          })
        );
        console.log(this.state.information);

You can't really push as it will mutate the state directly and that could potentially lead to error prone code, even if you are "resetting" the state again afterwards. 您不能真正进行推送,因为它会直接使状态发生变化,并且即使随后再“重置”状态也可能导致易于出错的代码。 F.ex, it could lead to that some lifecycle methods like componentDidUpdate won't trigger. 例如,它可能导致某些生命周期方法(例如componentDidUpdate)不会触发。

So with ES6 you can use spread operator. 因此,使用ES6,您可以使用传播算子。

this.setState(prevState => ({
    information: {
      country: [...state.information.country, "country1"],
      place:   [...state.information.place, "place1"]
    }
  })
);
console.log(this.state.information);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM