【发布时间】:2020-12-28 12:16:06
【问题描述】:
我正在尝试向状态数组添加一个新值,但它给了我错误。
代码
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 限制了嵌套更新的数量以防止无限循环。]
【问题讨论】:
-
您能举个例子说明 typeThree 对象/数组是什么吗?
-
typeThree 是一个数组
-
听起来你没有数组
-
它在错误中说,您在使用它之前没有处理承诺的成功或失败选项。
-
这几乎可以肯定是一个不完整的例子。要么是
await来自同步本机方法的响应,要么typeThree不是数组。本机方法返回新的长度,但您期望一个修改后的数组作为返回值,并且您的错误表明目标调用者上没有定义push。简而言之,我们需要更多细节。
标签: javascript reactjs react-native