如何使用反应更新数组中的项目?
How to update item in array using react?
你能告诉我如何使用 React 更新数组中的项目吗?我使用 add
按钮创建了一个动态列表。在生成的项目中,我有两个按钮 update
和 delete
。
单击更新按钮后,我将添加按钮的文本更改为 update
并在输入字段中填写所选值。现在,当我单击更新按钮时,我想更新所选项目。
这是我的代码
https://plnkr.co/edit/bpSGPLLoDZcofV4DYxPe?p=preview
addName() {
if (this.state.username !== '') {
if (this.state.btnText === 'add') {
this.props.add(this.state.username)
} else if (this.state.btnText === 'update') {
this.props.updateItem(this.state.username)
}
this.setState({
username: '',
btnText: 'add'
})
}
}
delete(item) {
this.props.deleteItem(item)
}
update(item){
this.setState({
username : item,
btnText:'update'
})
}
您需要将更新的项目名称和项目的索引传递给reducer中的更新案例。然后只需使用 splice 更新新值
更新了 plunkr。检查一下here
case 'UPDATE_ITEM':
let newList = state.slice()
newList.splice(action.payload.index, 1, action.payload.item)
return newList;
你能告诉我如何使用 React 更新数组中的项目吗?我使用 add
按钮创建了一个动态列表。在生成的项目中,我有两个按钮 update
和 delete
。
单击更新按钮后,我将添加按钮的文本更改为 update
并在输入字段中填写所选值。现在,当我单击更新按钮时,我想更新所选项目。
这是我的代码 https://plnkr.co/edit/bpSGPLLoDZcofV4DYxPe?p=preview
addName() {
if (this.state.username !== '') {
if (this.state.btnText === 'add') {
this.props.add(this.state.username)
} else if (this.state.btnText === 'update') {
this.props.updateItem(this.state.username)
}
this.setState({
username: '',
btnText: 'add'
})
}
}
delete(item) {
this.props.deleteItem(item)
}
update(item){
this.setState({
username : item,
btnText:'update'
})
}
您需要将更新的项目名称和项目的索引传递给reducer中的更新案例。然后只需使用 splice 更新新值
更新了 plunkr。检查一下here
case 'UPDATE_ITEM':
let newList = state.slice()
newList.splice(action.payload.index, 1, action.payload.item)
return newList;