在useState挂钩中反应设置状态

问题描述

我在使用useState挂钩更新状态时遇到问题。
因此,在“应用”组件中,我声明了对象数组状态:

const [panelSettings,setPanelSettings] = useState([
{
  title: 'Background',active: true,options: [],updateDaily: true
},{
  title: 'Time and Date',showSeconds: true
},{
  title: 'Weather Forecast',active: false,city: null
}])

然后我将{panelSettings}{setPanelSettings}传递给另一个组件,我们称之为“菜单”。
在此“菜单”组件中,我呈现每个标题并在其旁边具有一个复选框,该复选框应设置“ active”属性。像这样:

{panelSettings.map(element => {
   return (
     <div key={element.title}>
       {element.title}
       <input type='checkbox' checked={element.active} onChange={() => setPanelSettings(element.active = !element.active)} />
     </div>)
})}

但是,当我单击任何复选框时,会出现错误“ TypeError:无法读取未定义的'active'属性” 。但是,它来自我的父组件(“应用”),而不是来自“菜单”。
我尝试了多种方法来渲染元素并调用setPanelSettings函数,但到目前为止没有任何效果。我还从“菜单”组件中注销了该对象,似乎“活动”属性在那里已更改。

解决方法

这样做的时候

setPanelSettings(element.active = !element.active)

您正在将panelSettings

[{
  title: 'Background',active: true,options: [],updateDaily: true
},{
  title: 'Time and Date',showSeconds: true
},{
  title: 'Weather Forecast',active: false,city: null
}]

truefalse。显然不是您想要的。

可能您想做:

setPanelSettings((prevState) => prevState.map((s) => {
    if (s === element) {
        return { ...s,active: !s.active };
    }
    return s;
}))
,

您到底从哪里得到错误?是从onChange函数还是从选中的属性? 如果它在onChange函数中,则必须使用以前的状态来更新新状态,因此应该是这样的:

setPanelSettings((prevState) => {
   return prevState.map((menuInput) => {
       if (menuInput.title === element.title)
          return { ...menuInput,active: !menuInput.active };

       return menuInput;
   });
})
,

这些评论使我走上了正确的道路,最终的解决方案是:

{panelSettings.map(element => {
  return (
    <div key={element.title}>
      {element.title}
      <input type='checkbox' checked={element.active} onChange={() => {
        const next = [...panelSettings];
        next[index].active = !next[index].active;
        setPanelSettings(next);
      } />
    </div>)
})}

我确定这不是最复杂的方法,但是我真的不知道如何以更简洁的方式解决它并完成工作。因此,感谢大家的回答。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...