在 useState 钩子中反应设置状态 [英] React setting state in useState hook

查看:64
本文介绍了在 useState 钩子中反应设置状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 useState 钩子更新我的状态时遇到问题.
所以在我的应用程序"中组件,我声明我的对象数组状态:

I have problem with updating my state using useState hook.
So in my "App" component, I declare my array of objects state:

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

然后我将 {panelSettings}{setPanelSettings} 传递给另一个组件,我们称之为菜单".
在这个菜单"中组件我渲染每个标题并在它们旁边有一个复选框,它应该设置活动"财产.像这样:

Then I pass {panelSettings} and {setPanelSettings} down to another component, let's call it "Menu".
In this "Menu" component I render each title and have a checkbox next to them, which should set the "active" property. Like so:

{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 函数,但到目前为止没有任何效果.我还从菜单"中注销了对象.组件,似乎那里的活动"属性发生了变化.

But when I click on any of the checkboxes, I get the error "TypeError: Cannot read property 'active' of undefined". However, it comes from my parent component ("App") and not from the "Menu".
I've tried multiple ways to render out the elements and calling the setPanelSettings function but nothing has worked so far. I've also logged out the object from the "Menu" component and it seemed like the 'active' property has changed there.

推荐答案

评论让我走上了正轨,最终的解决方案是这样的:

The comments put me on the right track, and the final solution was this:

{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>)
})}

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

I'm sure it's not the most sophisticated, but I don't really know how it could be solved in a more concise way and it got the job done. So thanks everyone for the answers.

这篇关于在 useState 钩子中反应设置状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆