简体   繁体   English

使用速记更新对象和setState的数组

[英]update array of object and setState using shorthand

Was trying to rewrite my update array of object using shorter version but failed, I have a working version, which assign to a tempporary variable before setState. 试图使用较短的版本重写我的对象更新数组,但是失败了,我有一个有效的版本,该版本在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
    }))
})

You need to return the e.target.value or the o . 您需要返回 e.target.valueo As is, the inside of your map function is just an orphaned expression that's not connected to anything, which won't work. 照原样,您的map函数的内部只是一个孤立的表达式,未与任何东西连接,这是行不通的。

Best thing to do would be to have the arrow function implicitly return, by removing the { } s: 最好的办法是通过删除{ }来使arrow函数隐式返回:

this.setState({
  items: (this.state.templates || []).map((o, i) => (
    i === idx ? e.target.value : o
  ))
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM