简体   繁体   English

如何在 React 中使 state 不可变

[英]How to make state immutable in React

I am looking for the best way to make my handleSwitch + setState function immutable.我正在寻找使我的 handleSwitch + setState function 不可变的最佳方法。 The code I have currently works but is mutable and I am unsure how to make it immutable everything I have tried either doesn't work or gives me a syntax error.我目前使用的代码是可变的,但我不确定如何使它不可变我尝试过的所有东西要么不起作用,要么给我一个语法错误。

This is my state being initialised这是我的 state 正在初始化

this.state = {
      contacts: [],
      filteredContacts: [],
      selected: [],
      contactsSelection: {},
      loading: false,
    };

I have a simple <Switch /> comp which triggers the below when a user toggles the switch.我有一个简单的<Switch />组合,当用户切换开关时会触发以下内容。

handleSwitch = async (contact, added) => {
    if (added) {
      console.log('added', { contact, added });
      return this.setState(prevState => ({
        contactsSelection: {
          ...prevState.contactsSelection,
          [contact.id]: contact,
        },
      }));
    }

    console.log('removed', { contact, added });
    // const { contactsSelection } = this.state;
    return this.setState(prevState => {
      const existingSelection = { ...prevState.contactsSelection };
      delete existingSelection[contact.id]; // <-- make immutable
      return { contactsSelection: existingSelection };
    });
  };

just to clarify: your code is fine by now, it does not mutate state directly but mutates copy.只是为了澄清:你的代码现在很好,它不会直接改变 state 而是改变副本。

but if you'd like having that in different way, here is a pattern:但如果你想以不同的方式拥有它,这里有一个模式:

this.setState(prevState => {
      const { [contact.id]: unusedVariable, ...restContacts } =
          prevState.contactsSelection;
      return { contactsSelection: restContacts };
})

or with destructuring:或解构:

this.setState(
  ({ contactsSelection: {[contact.id]: unused, ...filteredContact} })) => 
      ({ contactsSelection: filteredContacts })
);

Anyway unfortunately there is no way to avoid introducing unusedVariable while destructuring.无论如何不幸的是,没有办法避免在解构时引入unusedVariable So it will need you to suppress ESLint warning "variable... is not used".所以它需要你抑制 ESLint 警告“变量......未使用”。

To me, your way handling that is better readable.对我来说,您的处理方式更具可读性。

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

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