试图使用较短的版本重写我的更新对象数组,但失败了,我有一个工作版本, 它在 setState 之前分配给临时变量。
//working version
const new_items = (this.state.new_items || []).map((o, i) => {
if(i === idx) {
return e.target.value
}
return o
})
this.setState({
items: new_items
})
//shorter version but why snytax error?
this.setState({
items: (this.state.items || []).map((o, i)=> ({
i === idx ? e.target.value : o
}))
})
最佳答案
您需要返回e.target.value
或o
。事实上,您的 map
函数的内部只是一个孤立的表达式,没有连接到任何东西,因此不起作用。
最好的办法是通过删除 {
}
来让箭头函数隐式返回:
this.setState({
items: (this.state.templates || []).map((o, i) => (
i === idx ? e.target.value : o
))
});
关于javascript - 使用简写更新对象数组和 setState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50710615/