Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 助手方法无法使用setState设置增量ID_Javascript_Reactjs_Ecmascript 6 - Fatal编程技术网

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,但它将按预期工作