我是javascript新手,但会做出反应,我尝试将新元素推入状态内的数组,但没有成功。
state = {
columns: [
{
id: 122,
items: [{text:'abc'},{text:'cde'}]
},
{
id: 143,
items: []
}
]
}
addItem(columnId,text) {
const newItem = {text: text}
//this.setState(...)
}
基本上,我有一个具有给定columnId和一些文本内容的addItem函数,我想将一个新项目推送到具有给定columnId的列内的items数组中。
我听说借助不变性帮助程序会容易得多,对吗?
最佳答案
如果您学习诸如map,filter和spread syntax或Object.assign之类的方法,则不需要任何不变性助手。使用其中一些(合适的),您可以做任何您想做的事情而不会改变状态。
const addItem = (columnId, text) => {
// We are mapping the columns from the state.
const newColumns = this.state.columns.map(column => {
// If id does not match just return the column.
if (column.id !== columnId) return column;
// Else, return a new column object by using spread syntax.
// We spread the column (preserve other properties, and create items again
// using spread syntax. Spread the items, add the new text object.
return { ...column, items: [...column.items, { text }] };
});
// Lastly, set the state with newColumns.
this.setState({ columns: newColumns });
};
没有评论:
const addItem = (columnId, text) => {
const newColumns = this.state.columns.map(column => {
if (column.id !== columnId) return column;
return { ...column, items: [...column.items, { text }] };
});
this.setState({ columns: newColumns });
};