React中useState无法按预期更新对象状态键的问题
问题分析与修复方案
问题根源
你的代码存在两个核心问题,直接导致了仅formula标签变红的现象:
- 多次setData触发状态覆盖:循环里每次校验都调用
setData,第二次更新formula类时,你依赖的是初始的data[key](未更新valueTextClass的版本),会把第一次对valueTextClass的更新覆盖,最终只有formula的类生效。 - 对象展开语法错误:代码里
(...prev是错误写法,正确的对象展开应该是{...prev},这个语法问题会直接导致运行报错。
修复后的代码
方案一:一次性构建更新对象(推荐)
先遍历所有字段,把需要更新的类名统一整理到新对象中,最后一次性调用setData,彻底避免多次更新的覆盖问题:
const validate = () => { // 移除无用的key参数 const updatedData = {...data}; Object.keys(data).forEach(key => { const currentItem = {...data[key]}; // 校验value字段 if (data[key].value === '') { currentItem.valueTextClass = 'text-red'; } else { // 可选:输入不为空时移除红色类 currentItem.valueTextClass = ''; } // 校验formula字段 if (data[key].formula === '') { currentItem.formulaInputClass = 'text-red'; } else { currentItem.formulaInputClass = ''; } updatedData[key] = currentItem; }); setData(updatedData); }
方案二:基于prev状态更新
如果坚持在循环内调用setData,必须每次都基于最新的prev状态进行更新,而不是依赖外部的data:
const validate = () => { Object.keys(data).forEach(key => { setData(prevState => { const currentItem = {...prevState[key]}; // 校验value if (prevState[key].value === '') { currentItem.valueTextClass = 'text-red'; } else { currentItem.valueTextClass = ''; } // 校验formula if (prevState[key].formula === '') { currentItem.formulaInputClass = 'text-red'; } else { currentItem.formulaInputClass = ''; } return { ...prevState, [key]: currentItem }; }); }); }
额外优化提示
- 移除validate函数中无用的
key参数,它和循环内的key变量重名,会导致变量覆盖。 - 优先使用
===进行严格相等判断,避免隐式类型转换引发的意外问题。
内容的提问来源于stack exchange,提问作者Pradhyumn Sharma
相关产品推荐
相关产品推荐

