简体   繁体   English

尝试动态更改 state 时意外更改 state

[英]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

Two problems:两个问题:

  1. The callback is not returning the updated state回调未返回更新后的 state
  2. state is mutated state发生变异

Fixed handler:固定处理程序:

const handleGroupToggle = (group) => {
  setGroupOpen((state) => ({ ...state, [group]: !state[group] }));
};

编辑 silly-snyder-el445g

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM