[英]setState not working for updating an array in React
I try to update a state
in a location object.我尝试更新位置对象中的
state
。 somehow the setState isn't working for me.不知何故 setState 对我不起作用。
The console.log
does return the newName correctly. console.log
确实正确返回了 newName。
I don't see directly where my fault is.我没有直接看出我的错在哪里。 Can someone tell me where my error is?
有人能告诉我我的错误在哪里吗?
state = {
locations: [
{name:"name1", address:"address1", locationSelected:false},
{name:"name2", address:"address2", locationSelected:false}
]
}
selectLocationHandler = (id) => {
let theLocations = [...this.state.locations];
theLocations[id] = {...theLocations[id], name:"newName!!!!"};
console.log(theLocations[id].name + "testtest");
this.setState({theLocations}, () => {
console.log(this.state.locations[id].name + " it worksss");
});
}
The main problem with this code is that your are altering a state object directly.此代码的主要问题是您正在直接更改状态对象。 You should treat all state objects as if they are immutable.
您应该将所有状态对象视为不可变的。 In your code, you do not actually need the
setState
call because the state would already be updated.在您的代码中,您实际上并不需要
setState
调用,因为状态已经更新。 When you define theLocations
, you are cloning the array, but not the objects in that array.当您定义
theLocations
,您是在克隆数组,而不是该数组中的对象。
To clone an array of objects, use this:要克隆一组对象,请使用以下命令:
const theLocations = this.state.locations.map(l => Object.assign({}, l));
Once you have your cloned array of objects, just set the name like this:获得克隆的对象数组后,只需像这样设置名称:
theLocations[id].name = "newName!!!!";
Another error here is that you are saving theLocations
as a new property in your state object.这里的另一个错误是您将
theLocations
保存为状态对象中的新属性。 You need to set locations
as the key in your setState
function:您需要在
setState
函数中将locations
设置为键:
this.setState({locations: theLocations}, () => {});
Complete code:完整代码:
selectLocationHandler = (id) => {
const theLocations = this.state.locations.map(l => Object.assign({}, l));
theLocations[id].name = "newName!!!!";
this.setState({locations: theLocations}, () => {
console.log(this.state.locations[id].name + " it worksss");
});
}
In setState you should specify name of property in the state which you want to update.在 setState 中,您应该指定要更新的状态中的属性名称。 In your case
{theLocations}
means that you have the next object {theLocations: theLocations}
.在您的情况下,
{theLocations}
意味着您拥有下一个对象{theLocations: theLocations}
。 You need to change it to: this.setState({locations: theLocations}, () => { console.log(this.state.locations[id].name + " it worksss"); });
您需要将其更改为:
this.setState({locations: theLocations}, () => { console.log(this.state.locations[id].name + " it worksss"); });
将数组重置为空,然后将状态设置为新值:
this.setState({ locations: [] }, () => this.setState({ locations: theLocations }))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.