Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
676 views
in Technique[技术] by (71.8m points)

reactjs - How to update array state in react native?

I am trying to update only one element in an array state but i am not sure of how to do it.

State

constructor(props) {
    super(props);
    this.state = {
        markers: [],
    };
} 

Setting the state

 setCurrentLocation() {
    var root = this;
    root.setState({
        markers: [
            ...root.state.markers,
            {
                coordinate: {
                    latitude: parseFloat(root.state.currentLat),
                    longitude: parseFloat(root.state.currentLon)
                },
                key: root.state.currentLat,
                image: pinCurrentLocation

            },
        ],
    });
}

If i want to change the key in the fourth element of marker, how do i do that?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Important point is, we should not mutate the state array directly, always do the changes in new array and then use setState to update the state value.

As suggested by Doc:

Never mutate this.state directly, Treat this.state as if it were immutable.

Basic flow of updating a state array is:

1- First create the copy of state array.

2- Find index of the item (if index is available skip this one).

3- Update the value of item at that index.

4- Use setState to update the state value.


Multiple solutions are possible:

1- Use array.map and check which element you want to update, when you find that element return a new object for that with updated key value otherwise just return the same object. Like this:

let newMarkers = markers.map(el => (
      el.name==='name'? {...el, key: value}: el
))
this.setState({ markers });

2- We can also use array.findIndex to find the index of that particular item, then update the values of that item. Like this:

let markers = [...this.state.markers];
let index = markers.findIndex(el => el.name === 'name');
markers[index] = {...markers[index], key: value};
this.setState({ markers });

Loop will be not required if we know the index of the item, directly we can write:

let markers = [ ...this.state.markers ];
markers[index] = {...markers[index], key: value};
this.setState({ markers });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...