简体   繁体   中英

Setstate of specific object in array

I have a cats array that I pull from an api

i map over these and render them on a page

each one gets rendered with a like button, when I hit like I want it to like it and when i hit like again, it should unlike it

my initialState is :

  state = {
    cats: []
  };

then once i call the api state looks like this:

cats: [
    {url: Array(1), id: Array(1), source_url: Array(1), liked: false}
    {url: Array(1), id: Array(1), source_url: Array(1), liked: false}
]

I have a like cat method whereby I find the cat that I liked like this:

var cat = this.state.cats.find(c => c.id[0] === cat.id[0])

considering I have all this information, how do I call setState for that specific cat to change the liked from false to true?

I was thinking something like this:

   this.setState(prevState => ({ cats: {
      cat: {
        ...prevState.cat,
        liked: !prevState.cat.liked
      }
    }}))

but it does not know what liked is of undefined

any ideas?

One problem with your approach is that there's no prevState.cat .

Assuming the (un)liked cat is stored in cat :

this.setState(prevState => ({
    cats: prevState.cats.map(c => c.id[0] === cat.id[0] ? Object.assign(c, { liked: !c.liked }) : c)
}));

Demo:

 var state; function setState(a) { state = Object.assign(state, a(state)); } state = { cats: [ {url: [0], id: [1], source_url: [0], liked: false}, {url: [0], id: [2], source_url: [0], liked: false} ] }; var cat = state.cats[1]; setState(prevState => ({ cats: prevState.cats.map(c => c.id[0] === cat.id[0] ? Object.assign(c, { liked: !c.liked }) : c) })); console.log(state.cats[1].liked); 

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