React中如何从组件向数组对象类型的State传递值
解决React数组对象State的子组件更新问题
要实现子组件SimpleComponent的值同步到父组件的Value数组State,核心是不可变地更新数组中对应索引的对象——直接修改原State不会触发组件重渲染,必须生成新的数组/对象引用。
修改后的父组件映射代码
{Value.map((item, i) => { return ( <div key={i}> <SimpleComponent Width={item.Width} // 更新对应索引的Width值 setWidth={(newWidth) => { setValue(prev => { // 复制原数组,避免直接修改 const newArr = [...prev]; // 创建新对象替换原索引项,保证不可变性 newArr[i] = {...newArr[i], Width: newWidth}; return newArr; }); }} Length={item.Length} // 更新对应索引的Length值 setLength={(newLength) => { setValue(prev => { const newArr = [...prev]; newArr[i] = {...newArr[i], Length: newLength}; return newArr; }); }} /> </div> ) })}
关键说明
- 使用
setValue的函数式更新(接收prev作为当前State),确保获取最新的State值,避免闭包导致的旧值问题。 - 通过
[...prev]复制原数组、{...newArr[i]}复制原对象,再修改目标属性,保证每次更新都生成新引用,触发React重渲染。 - 若数组项结构复杂,也可以用
Array.map简化写法:setWidth={(newWidth) => { setValue(prev => prev.map((curr, idx) => idx === i ? {...curr, Width: newWidth} : curr )); }}
内容的提问来源于stack exchange,提问作者s.kuznetsov
相关产品推荐
相关产品推荐

