试图更新状态。 setState无法正常工作。.
这是功能和状态:
state = {
security: {
0: { id: "54321", name: "test1"}
1: { id: "98765", name: "test2"}
}
}
removeSecInState = (security) => () => {
var temp = Object.assign({}, this.state.security)
var temp1 = Object.values(temp)
var index = temp1.findIndex(id => id.id === security.id) //getIndex
delete temp[0]
this.setState({security: temp},() => {
console.log(temp, "inside");
console.log(this.state.security, "inside1")
})
}
console.log(temp, "inside") =
security: {
1: { id: "98765", name: "test2"}
}
console.log(this.state.security, "inside1") =
security: {
0: { id: "54321", name: "test1"}
1: { id: "98765", name: "test2"}
}
不知何故,状态不会更新为与temp相同,总是返回到先前的状态
答案 0 :(得分:-1)
您似乎没有在状态前加入this
关键字,您也应该
尝试一下
this.state = {
security: {
0: { id: "54321", name: "test1"}
1: { id: "98765", name: "test2"}
}
}
另外,您应该尝试重构代码
也许是这样
this.state = {
security: [
{ id: "54321", name: "test1"},
{ id: "98765", name: "test2"}
]
}
removeSecInState(sec) {
this.setState({
security: this.state.security.filter(item => item.id !== sec.id)
})
}