Javascript 使用SetState更新react中数组对象中的一个项
我有一个名为items的state对象Javascript 使用SetState更新react中数组对象中的一个项,javascript,reactjs,Javascript,Reactjs,我有一个名为items的state对象 items: [ { name: 'John' id: '1', checked: false, }, { name: 'Dude' id: '2', checked: true, } ] 在UI单击时,我需要将id为1的项的checked属性更新为true 如何使用项目的设置状态更新项目中的一个项目?评论中的解释: const {items} = t
items: [
{
name: 'John'
id: '1',
checked: false,
},
{
name: 'Dude'
id: '2',
checked: true,
}
]
在UI单击时,我需要将id为1的项的checked属性更新为true
如何使用项目的设置状态更新项目中的一个项目?评论中的解释:
const {items} = this.state;
const index = items.findIndex(val=>val.id ===1);
items[index].checked = true;
this.setState({items});
onClick(id) {
// Create a temporary copy of your items array
const itemsCopy = this.state.items.slice();
// Find the index of the items where the item has the id you want
const idx= itemsCopy.findIndex(x => x.id === id);
// Re-assign the item to have the same values as before (name and id), but change the checked to true
itemsCopy[idx] = {...itemsCopy[idx], checked: true};
// Update the state with our modified copy
this.setState({items: itemsCopy});
}
像这样的?评论中的解释:
onClick(id) {
// Create a temporary copy of your items array
const itemsCopy = this.state.items.slice();
// Find the index of the items where the item has the id you want
const idx= itemsCopy.findIndex(x => x.id === id);
// Re-assign the item to have the same values as before (name and id), but change the checked to true
itemsCopy[idx] = {...itemsCopy[idx], checked: true};
// Update the state with our modified copy
this.setState({items: itemsCopy});
}
应更新处于状态的“items”对象。所以切片可以用来复制数组。 将其设置回状态就足够了,这样组件就可以理解状态已更改
let items = this.state.items.slice();
const index = items.findIndex(val => val.id === 1);
items[index].checked = true;
this.setState({ items });
应更新处于状态的“items”对象。所以切片可以用来复制数组。 将其设置回状态就足够了,这样组件就可以理解状态已更改
let items = this.state.items.slice();
const index = items.findIndex(val => val.id === 1);
items[index].checked = true;
this.setState({ items });
可能的重复可能的重复