【问题标题】:Muting previousState to set the new State in React静音 previousState 以在 React 中设置新状态
【发布时间】:2018-08-23 10:12:34
【问题描述】:

我正在根据 previousState 更改 React 中的状态。基本上我正在从一组项目中删除一个项目,我想要最好的最简单的方法。

这很有效,但也许不是最佳做法?

handleItemsRemove = (id, index) => {
    if (index === -1) {
      return;
    }
    this.setState(
      previousState => {
        const { items } = previousState;
        items.splice(index, 1);
        return {
          items
        };
      }
    );
  };

在 React 重写 previousState 的方式中,此代码是否存在任何涉及可变性等的问题? previousState 是可变的吗,即使是这样,这样做可以吗?

否则您认为处理这种情况的最佳方法是什么?

【问题讨论】:

    标签: javascript arrays reactjs state splice


    【解决方案1】:

    方法 splice 修改原始数组 - 所以这不是您需要的方式。

    相反,您可以过滤掉不需要的项目。请阅读更多关于创建新数组的filter 方法。

    您也不需要为整个状态创建变量。相反,您可以使用destructuring:

    handleItemsRemove = (id, index) => {
      if (index === -1) {
        return;
      }
    
      this.setState(({items}) => ({
        items: items.filter((item, itemIndex) => index !== itemIndex),
      }));
    };
    

    【讨论】:

    • 我不喜欢这个解决方案的地方是它循环遍历整个数组,而我已经知道在哪里删除。
    【解决方案2】:

    来自React docs

    永远不要直接改变this.state,因为之后调用setState() 可能会替换你所做的改变。将 this.state 视为不可变的。

    我不确定这是否适用于您的情况,但为了安全起见,请构建一个全新的对象。您可以使用items.slice(0, index) 来获取index 之前的数组部分和items.slice(index + 1) 获取index 之后的部分,然后spread 将它们放在一个新数组上:

    handleItemsRemove = (id, index) => {
      if (index === -1) {
        return;
      }
      this.setState(
        ({items}) => ({
          items: [
            ...items.slice(0, index),
            ...items.slice(index + 1)
          ]
        })
      );
    };
    

    【讨论】:

    • 确实如此。我在考虑 Redux。
    • 哦,我看.. 我不使用 Redux :) 但是当你使用 setState,所以你可以 100% 依赖该状态将被合并,无需传播其他人..which没有从这个地方改变。
    • 我已经删除了我的答案,但我可以帮助你另一个想法.. 而不是创建这么多中间数组.. 做previousState.items.slice().splice(index, 1)...它更干净,更快..跨度>
    • @ArupRakshit 很好的答案。您应该将此添加为新答案。我认为它实际上是最好的
    猜你喜欢
    • 2018-11-24
    • 2022-11-29
    • 1970-01-01
    • 2017-08-17
    • 2017-05-30
    • 2017-07-18
    • 2018-12-10
    • 2019-01-19
    • 1970-01-01
    相关资源
    最近更新 更多