[英]React state changing unexpectedly when trying to dynamically change state
I have certain routes defined in routes.tsx
.我在routes.tsx
中定义了某些路线。
I am using this to dynamically populate a sidebar (Material UI Drawer).我正在使用它来动态填充侧边栏(Material UI Drawer)。
The routes have the following structure:路由具有以下结构:
const AppRoutes = {
group_a: {
title: "",
icon: <material icon JSX>,
path: "",
children: {
...same structure as a group, but without further children
}
}
}
After getting the routes, I created a state object to keep track of expanding/collapsing the groups.获取路线后,我创建了一个 state object 来跟踪扩展/折叠组。
let menuGroups = Object.keys(AppRoutes);
const [groupOpen, setGroupOpen] = React.useState(() => {
const state = {};
for (let group of menuGroups)
(state as any)[group] = true;
return state;
});
const handleGroupToggle = (group: string) => {
setGroupOpen(state => (state as any)[group] = !(state as any)[group]); // something wrong here? idk
};
But this isn't working as expected.但这没有按预期工作。
Initially the groups are open as expected.最初,这些小组是按预期开放的。 But on clicking any group, all groups collapse together.但是在单击任何组时,所有组都会一起折叠。 And then another attempt to re-open them results in an error.然后再次尝试重新打开它们会导致错误。 Uncaught TypeError: Cannot create property 'group_a' on boolean 'false'
On further investigation, I found that the state object has somehow become just a boolean false
.在进一步调查中,我发现 state object 不知何故变成了 boolean false
。
Here's a codesandbox to replicate this:https://codesandbox.io/s/flamboyant-rgb-oin62u?file=/src/App.js这是一个复制此代码的代码框:https://codesandbox.io/s/flamboyant-rgb-oin62u?file=/src/App.js
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.