[英]How to update an object in an array of Objects using setState
我正在使用React,我的狀態被定義為一個對象數組。 我需要能夠只更改state.data數組中的一個特定元素,id為1的示例對象。
我想知道:
setState()
的正確方法是什么。 constructor(props) { super(props); this.state = { data: [{ id: 0, title: 'Buy a', status: 0, // 0 = todo, 1 = done }, { id: 1, title: 'Buy b', status: 0, }, { id: 2, title: 'Buy c', status: 0, } ] }; this.onTitleChange = this.onTitleChange.bind(this); } onTitleChange(id, title) { console.log(id, title); debugger }
您可以使用spread運算符克隆狀態對象,然后使用findIndex
方法在給定id的數組中查找對象的索引修改對象並設置狀態。
constructor(props) {
super(props);
this.state = {
data: [{
id: 0,
title: 'Buy a',
status: 0, // 0 = todo, 1 = done
},
{
id: 1,
title: 'Buy b',
status: 0,
},
{
id: 2,
title: 'Buy c',
status: 0,
}
]
};
this.onTitleChange = this.onTitleChange.bind(this);
}
onTitleChange(id, title) {
var data = [...this.state.data];
var index = data.findIndex(obj => obj.id === id);
data[index].title = title;
this.setState({data});
}
你也可以這樣做:
onChange = (id, value, field) => {
this.setState((prevState) => ({
data: prevState.data.map((d, index) => { //d = object, index = index in array
if (d.id === id) {
return {
...d,
[field]: value //field/name in object
}
}
return d
})
}), () => {
console.log("New value of", field, "=", value, "in object with id", id);
});
}
您也可以修改自己的方式
以下面的格式存儲狀態
為了方便,希望這有幫助!
constructor(props) {
super(props);
this.state = {
data: [
0: {
id: 0,
title: 'Buy a',
status: 0, // 0 = todo, 1 = done
},
1: {
id: 1,
title: 'Buy b',
status: 0,
},
2: {
id: 2,
title: 'Buy c',
status: 0,
}
]
};
this.onTitleChange = this.onTitleChange.bind(this);
}
onTitleChange(id, title) {
var newData = [...this.state.data];
newData[id].title = title;
this.setState({newData});
}
一個簡單的解決方案是:
const idx = this.state.data.findIndex(obj => obj === id);
this.state.data[idx].title = title;
對於更復雜的組件,我建議使用Immutable.js List
我會使用spread運算符來更新狀態。
onTitleChange(id, title) {
const { data } = this.state
const index = data.findIndex(d => d.id === id)
this.setState({
data: [
...data.slice(0, index),
{
...data[index],
title: title,
},
...data.slice(index + 1)
]
})
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.