【发布时间】:2020-11-30 08:29:54
【问题描述】:
我在使用 useState 挂钩更新状态时遇到问题。
所以在我的“App”组件中,我声明了我的对象数组状态:
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} 传递给另一个组件,我们称之为“菜单”。
在这个“菜单”组件中,我呈现每个标题并在它们旁边有一个复选框,它应该设置“活动”属性。像这样:
{panelSettings.map(element => {
return (
<div key={element.title}>
{element.title}
<input type='checkbox' checked={element.active} onChange={() => setPanelSettings(element.active = !element.active)} />
</div>)
})}
但是当我点击任何复选框时,我会收到错误“TypeError: Cannot read property 'active' of undefined”。但是,它来自我的父组件(“应用程序”),而不是来自“菜单”。
我尝试了多种方法来渲染元素并调用setPanelSettings 函数,但到目前为止没有任何效果。我还从“菜单”组件中注销了该对象,似乎“活动”属性在那里发生了变化。
【问题讨论】:
-
你可以参考这个。我相信它涵盖了您的情况:stackoverflow.com/questions/55823296/…。 useState 不会合并对象的所有值。
-
你能看到标题吗?
-
是的,在我点击其中一个复选框之前一切正常
标签: javascript reactjs react-hooks use-state