国家
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>
)}
handleChange() 函数
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?
*/
}
对于解决方案的任何替代建议是
答案 0 :(得分:0)
您的代码有错误。要存储您应该使用的状态。
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 的值,并且其中没有 set 函数。它用于阅读