javascript - 更新深层嵌套 .map 中的状态值
问题描述
国家
const [config, setConfig] = useContext(ConfigContext)
配置状态上的 .map
{config[categoryNumber]?.config?.map((x: ConfigParam, i: number) =>
<tr key={i}>
<td>{x?.desc}</td>
<Switch
checked={x.value}
onChange={handleChange()}
/>
<td>{x?.unit}</td>
</tr>
)}
处理改变()函数
const handleChange = () => {
/*
The desire is that this function will update the value of the original array(the config state)
What is the best practice for achieving this behavior?
*/
}
解决方案的任何替代建议是
解决方案
您的代码有错误。要存储您应该使用的状态。
useState而不是useContext,useContext主要是为了避免道具钻孔。
所以你的代码应该是:
const [config, setConfig] = useState(ConfigContext)
handleChange(){
setConfig(prevConfigContext=> ({...prevConfigContext, children: 'Changed'})
}
如果您想知道useContext会做什么。
请阅读: https ://reactjs.org/docs/hooks-reference.html#usecontext
简而言之,这个函数(钩子)在树中暴露了先前的 Context.Provider 的值,并且其中没有设置函数。它用于阅读
推荐阅读
- javascript - 从数据库中填充选择框并添加重复行
- reactjs - 如何在 onclick 上进行调度和功能
- java - 获取 MismatchedInputException:在将 JSON 解析为结果对象时无法反序列化 Object 的实例
- php - 如何在 PHP 中合并选定的数组元素?
- mysql - 如何打破 While 循环 - 出现错误:语法错误:缺少“冒号”
- python - Cloud Firestore 中存储的数据值不正确
- r - 在 R 中的 ggplot 2 中使用更多数据帧
- javascript - 如何获取多个输入字段的 ID 并将它们汇总在一个跨度中
- scala - 在 Scala 中测试异常
- python - 如何修复pytorch中的“输入和隐藏张量不在同一设备上”