简体   繁体   中英

Add new values to existing state - React Native

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

This 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.

So with ES6 you can use spread operator.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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