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

React中使用useState更新数组时如何保留原有历史值?

问题原因

你当前的代码问题出在handleOnChange逻辑中:每次仅拆分当前正在输入的输入框内容,直接用这部分拆分结果覆盖content数组,自然会出现切换输入框时内容被重置的问题,没有收集所有输入框的单词。

解决方法

每次输入框内容更新后,遍历所有输入框的内容,统一拆分、过滤空值后合并赋值给content即可。修改后的handleOnChange代码如下:

const handleOnChange = (e, idx) => {
  const newField = [...fields];
  newField[idx].value = e.target.value;
  setFields(newField);

  // 遍历所有输入框,收集所有非空单词
  const allWords = newField.flatMap(field => {
    // 拆分后过滤空字符串,避免连续空格/空输入框产生空元素
    return field.value.split(' ').filter(word => word.trim() !== '')
  })
  setContent(allWords);
};

如果担心flatMap的兼容性,也可以用更基础的遍历写法实现相同效果:

const handleOnChange = (e, idx) => {
  const newField = [...fields];
  newField[idx].value = e.target.value;
  setFields(newField);

  const allWords = []
  newField.forEach(field => {
    const words = field.value.split(' ').filter(word => word.trim() !== '')
    allWords.push(...words)
  })
  setContent(allWords);
};

效果验证

按你的示例输入:第一个框输入lorem ipsum dolar,第二个框输入sit amet,最终content会自动合并为['lorem', 'ipsum', 'dolar', 'sit', 'amet'],完全符合需求。

内容的提问来源于stack exchange,提问作者Reinier68

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 05:39:05