繁体   English   中英

setState不会更新状态,即使在其回调react-native中也是如此

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

在这里,user_res已更新,但未更新状态,我也尝试将此功能绑定到此。 但结果相同:(

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)
});

我不认为user_res也没有更新。 map不会更新原始变量。 您需要将.map的值分配给某些内容。

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

如果检查文档形式为Array.prototype.map() ,您将看到map不会修改原始数组,它会返回一个包含修改后的项目的新数组。

map()方法创建一个新数组 ,并在调用数组中的每个元素上调用提供的函数。

因此,利用这些信息,您可以相应地修改代码,

// 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)
});

附言:您的代码段中未定义任何stats 如果您没有在共享代码段不包含的代码中定义它,那么可以,但是否则您也需要修复该部分。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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