首页 > 解决方案 > 如何向数组状态添加值?

问题描述

我正在尝试向状态数组添加一个新值,但它给了我错误。

代码

async shouldComponentUpdate(prevProps) {
    if (prevProps.navigation.state.params.updated) {
      const { updated } = prevProps.navigation.state.params;
      // updated = object
      const { typeTwo, typeThree } = this.state;
      const typeTwoUpdated = await typeTwo.filter((v) => v.id !== updated.id);
      const typeThreeUpdated = await typeThree.push(updated);
      this.setState({ typeTwo: typeTwoUpdated, typeThree: typeThreeUpdated });
    }
  }

错误

> [Unhandled promise rejection: TypeError: typeThree.push is not a function. (In 'typeThree.push(updated)', 'typeThree.push' is undefined)]

编辑

更改了代码。

async shouldComponentUpdate(prevProps) {
    if (prevProps.navigation.state.params.updated) {
      const { updated } = prevProps.navigation.state.params;
      // updated = object
      const { typeTwo, typeThree } = this.state;
      // typeThree = []
      const typeTwoUpdated = typeTwo.filter((v) => v.id !== updated.id);
      this.setState({ typeTwo: typeTwoUpdated, typeThree: [...typeThree, updated] });
    }
  }

新错误

[未处理的承诺拒绝:错误:超过最大更新深度。当组件在 componentWillUpdate 或 componentDidUpdate 中重复调用 setState 时,可能会发生这种情况。React 限制了嵌套更新的数量以防止无限循环。]

标签: javascriptreactjsreact-native

解决方案


检查初始状态,特别是 state.typeThree。shouldComponentUpdate可以在调用 this.setState({typeThree: Array}) 之前运行

编辑:请不要将项目添加到 React 组件状态中引用的数组中。
const typeThreeUpdated = typeThree && typeThree.length ? [...typeThree] : [];

typeThreeUpdated.push(updated);

this.setState({ typeTwo: typeTwoUpdated, typeThree: typeThreeUpdated });

编辑2:所以这就是发生的事情

const typeThreeUpdated = await typeThree.push(updated);

此行将导致 typeThreeUpdated 为整数值,即推送新元素后 typeThree 的新长度。改变数组但不返回新push数组,而是返回新长度。然后它被存储typeThree在这一行中的状态

this.setState({ typeTwo: typeTwoUpdated, typeThree: typeThreeUpdated });

并且在下一次函数运行时,this.state.typeThree 仍然是那个数字,没有推送功能。

await注意这里不需要


推荐阅读