【问题标题】:.unshift is not a function.unshift 不是函数
【发布时间】:2021-10-27 07:06:14
【问题描述】:

我刚开始学习 React JS,并且正在尝试一个简单的项目,我点击一个按钮并将一个随机数添加到一个数组中。这是我的代码:

function App() {
  
  const [cache2, setCache2] = useState([])

  const nextNumber = () => {
    const randomNr = Math.floor(Math.random() * 10)
    const newCache = cache2.push(randomNr)
    setCache2(newCache)    
    console.log(cache2)
  }

  return (
    <div className='App'>

      <button onClick = {nextNumber}>Next Number</button>
    </div>
  );
}

但是,它会引发“cache2.push 不是函数”错误。我无法找出问题所在。有人可以帮帮我吗?

【问题讨论】:

  • const newCache = cache2.push(randomNr) Push 返回一个添加的元素,而不是一个新数组
  • 永远不要推送状态,因为推送会改变原始数组并且在反应状态下不应该直接改变。你需要这样做 setCache2(currentCache =&gt; ([...currentCache, randomNr]))

标签: arrays reactjs push


【解决方案1】:

Array#push() 是一个变异函数,它返回你推送的元素,而不是原始数组。因此setCache2(newCache) 使cache2 成为一个非数组的数字。因此,从号码中调用 push() 会引发此错误。

最好新建一个数组并使用spread operator设置状态:

const nextNumber = () => {
  const randomNr = Math.floor(Math.random() * 10)
  setCache2([...cache2, randomNr])
  console.log(cache2)
}

【讨论】:

    猜你喜欢
    • 2015-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    相关资源
    最近更新 更多