简体   繁体   中英

Reactjs filter state by key and value

React Newbie here.

I'm trying to match the value of a specific id located in my state, so I can change some value before updating the database via my api.

The state is

state = {
library: []
}

and then with when the axios changes the state the array looks something like:

0:{_id:"", time:"", value:""},
2:{_id:"", time:"", value:""}

When I run console.log, it reads it like this.

(2) [{…}, {…}]0: {_id: "5c82803ad634ea0bebfb3eff", time: "2019-03-08T14:46:18.663Z", value:""}1: {_id: "5c827fb9d634ea0bebfb3efe", time: "2019-03-08T14:44:09.818Z", value:""}

So basically when I type in a specific input field, identified by it's _id, I need to update the value state of that specific state.

Here's the code I have written so far. _id is the unique key of the input field and event value what I'm typing.

updateRead = (_id, event) => {
    console.log(_id);
    console.log(event.target.value)
    this.setState(?????)
};

Help would be much appreciated!

Cheers

You can use the array map method on the library array in your state, and just return the elements as is if the _id doesn't match, and update the value if the _id does match.

updateRead = (_id, event) => {
  const { value } = event.target;

  this.setState(prevState => ({
    library: prevState.library.map(read => {
      if (read._id !== _id) {
        return read;
      }
      return {
        ...read,
        value
      };
    })
  }));
};

Two of the fundamental rules of state in React are:

Separately, you can't access properties on the synthetic event after the event handler has returned, so you'll want to grab the value before calling setState (since the call to your callback will be asynchronous).

Within the callback, you copy the array, find the relevant object, copy it, and set the value.

So:

updateRead = (_id, event) => {
    const {value} = event.target;
    this.setState(({library}) => ({
        library: library.map(entry => entry._id === _id ? {...entry, value} : entry)
    }));
};

map creates a new array from the previous array's entries. The callback returns a new object if the IDs match (using property spread notation) with an updated value , or the original object (since we don't have to copy objects we aren't modifying).

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