首页 > 解决方案 > 更新深层嵌套 .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? 
    */
    }
    

配置状态对象
配置状态对象

解决方案的任何替代建议是

标签: javascriptreactjstypescript

解决方案


您的代码有错误。要存储您应该使用的状态。

useState而不是useContextuseContext主要为了避免道具钻孔。

所以你的代码应该是:

const [config, setConfig] = useState(ConfigContext)

handleChange(){

setConfig(prevConfigContext=> ({...prevConfigContext, children: 'Changed'})

}

如果您想知道useContext会做什么。

请阅读: https ://reactjs.org/docs/hooks-reference.html#usecontext

简而言之,这个函数(钩子)在树中暴露了先前的 Context.Provider 的值,并且其中没有设置函数。它用于阅读


推荐阅读