You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中使用扩展运算符更新useState数组未达到预期效果的问题求助

React中使用扩展运算符更新useState数组未达到预期效果的问题求助

大家好,我最近在写一个React计算器组件,遇到了数组状态更新的问题,折腾了好一会儿没搞定,来求助各位前辈。

先贴一下我的组件代码:

import { useState } from 'react';

export default function Calculator(props){
  const [userInput, setUserInput] = useState('')
  const [operator,setOperator]= useState('')
  const [equationNumbers,setEquationNumbers] = useState([])
  const [result, setResult]= useState(0)

  /* 对数组元素执行加减乘除操作 */
  function Calculate(operator){
    /* 加法操作 */
    if (operator === '+'){
      setResult(equationNumbers[0] + equationNumbers[1])
      setUserInput(result)
    }
  }

  /* 处理按钮或键盘触发的操作 */
  function handleAddingOperation(e){
    e.preventDefault()
    repeatPressingOperation('if you want possitive number, use plaeas the switch button')
    setOperator('+')
    // equationNumbers.push(Number(userInput)) 之前用push是可以的,但知道不能直接修改状态
    let NewNum = [Number(userInput)]
    setEquationNumbers(NewNum)
    console.log(NewNum)
    setUserInput('')
  }

  function handlePressingEnterKeyOrEquallButton(e){
    e.preventDefault()
    repeatPressingOperation('you did not enter any number please try again')
    let NewNum = [
      ...equationNumbers,
      Number(userInput)
    ]
    setEquationNumbers([
      ...NewNum,
      Number(userInput)
    ])
    setUserInput('')
    console.log(NewNum)
    console.log(equationNumbers)
    Calculate(operator)
    clearAllData()
  }

  /* 处理键盘输入的操作符和回车 */
  function handleKeyDown(e){
    if(e.key === '+'){
      handleAddingOperation(e)
    }
    else if(e.key === 'Enter'){
      handlePressingEnterKeyOrEquallButton(e)
    }
  }

  // 这里省略了repeatPressingOperation和clearAllData的实现
}

我的问题是:我想让equationNumbers数组存储两个数——用户按下+号前输入的第一个数,以及按下回车时输入的第二个数。之前用push方法直接修改数组是能得到正确结果的,但我知道React里不能直接修改状态,所以改成用扩展运算符创建新数组来更新状态,结果现在打印equationNumbers的时候,它始终只有一个元素,就是最后一次输入的userInput,完全达不到我想要的效果。

比如用户先输入10,按下+,再输入20,按下回车,我期望equationNumbers是[10,20],但实际打印出来只有[20],这到底是哪里出问题了?麻烦各位帮我看看,谢谢啦!

备注:内容来源于stack exchange,提问作者built_Different_Developer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.22 14:59:49