简体   繁体   中英

setState is not updating the state, even in its callback react-native

here the user_res is updated but not the state, and I have tried binding this function to this also. but same result :(

let user_res = usr_vote;
user_res.map((vote)=>{
  if(vote.id==dat_id){
    vote.status = stats
  }
})
console.log("update user response:",user_res)
this.setState({user_response:user_res},()=>{
  console.log("but this is not uodating : ",this.state.user_response)
});

I don't think even user_res is updating. map doesn't update the original variable. You need to assign the value of .map to something.

user_res = user_res.map((vote)=>{
            if(vote.id==dat_id){
                return {...vote, status: stats}
            } else {return vote}
        })

If you check documentation form Array.prototype.map() , you will see that map doesn't modify the original array, it returns a new array with the modified items.

The map() method creates a new array with the results of calling a provided function on every element in the calling array.

So with that information you can modify your code accordingly,

// create a new array with the modified items
let user_res = usr_vote.map((vote) => {
  if(vote.id == dat_id){
    vote.status = stats
  }
});
// update state with the new array
this.setState({user_response:user_res},()=>{
  console.log("but this is not uodating : ",this.state.user_response)
});

PS: stats is not defined anywhere in your snippet. If you are not defining it somewhere in your code that your shared snippet doesn't contain, it is OK but otherwise you need to fix that part too.

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