Javascript 助手方法无法使用setState设置增量ID
我的组件中有这个Javascript 助手方法无法使用setState设置增量ID,javascript,reactjs,ecmascript-6,Javascript,Reactjs,Ecmascript 6,我的组件中有这个 addGift = () => { const { gifts } = this.state this.setState({ gifts: [ ...gifts, { id: max_number(...gifts.map(gift => gift.id)) + 1 } ] }) } 其中max_number是一个小助手 export const max_number = (ar
addGift = () => {
const { gifts } = this.state
this.setState({
gifts: [
...gifts,
{ id: max_number(...gifts.map(gift => gift.id)) + 1 }
]
})
}
其中max_number是一个小助手
export const max_number = (arr = []) => {
return arr.length > 0 ? Math.max(...arr) : 0
}
每当我启动addGift时,我将继续使用
{id:1}
,我希望它应该使用max\u number helper进行递增,但它没有。函数采用数组,因此在调用它时不应使用扩展语法:
{ id: max_number(gifts.map(gift => gift.id)) + 1 }
max_number接受无穷多个参数而不是数组,您可以像这样使用addGrid函数
addGift = () => {
const { gifts } = this.state
this.setState({
gifts: [
...gifts,
{ id: max_number(gifts.map(gift => gift.id)) + 1 }
]
})
}
或者,您可以在max_number函数F.ex中使用扩展运算符
export const max_number = (...arr) => {
return arr.length > 0 ? Math.max(...arr) : 0
}
…
不是操作员。这也不会是一种“蔓延”的情况。您正在收集此参数中的所有剩余参数。这是一个rest参数。是的,它是rest,但它将按预期工作