首页 > 解决方案 > 为什么我们需要将 this 变量设置为展开运算符?需要这条线吗?

问题描述

在下面的代码中,我不明白为什么我们需要下面的行,如果 counters 已经等于状态。在做什么?我可以删除该行吗?

counters[index] = { ...counters[index] };

这就是全部。

class App extends Component {
      state = {
        counters: [
          { id: 1, value: 0 },
          { id: 2, value: 0 },
          { id: 3, value: 0 },
          { id: 4, value: 0 }
        ]
      };

      handleIncrement = counter => {
        const counters = [...this.state.counters];
        const index = counters.indexOf(counter);
        counters[index] = { ...counters[index] };
        counters[index].value++;
        this.setState({ counters });
      };

标签: reactjs

解决方案


最初的意图似乎是创建一个看起来与原始对象相同的新对象(复制所有属性),但这样做是为了避免改变原始状态。

我怀疑如果没有这条线,它似乎“工作正常”,但 React 状态旨在是不可变的。

例如参见:https ://flaviocopes.com/react-immutability/


推荐阅读