javascript - 如何向数组状态添加值?
问题描述
我正在尝试向状态数组添加一个新值,但它给了我错误。
代码
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 限制了嵌套更新的数量以防止无限循环。]
解决方案
检查初始状态,特别是 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
注意这里不需要
推荐阅读
- gitlab-ci - Gitlab runner immediately fails & doesn't create the build folder. Works well when its run on debug mode
- java - open URL with Java in background
- python - Detecting audio inside audio [Audio Recognition]
- python - 如何将 [numpy.ndarray of ndarrays] 转换为一个 ndarray 数字
- python - How to open multiple files whose name has a special characters in it in python
- tensorflow - How to choose num_words parameter for keras Tokenizer?
- javascript - Trying to push StackScreen in React Native
- javascript - 隐藏元素时停止/防止页面/正文高度变化
- javascript - 从 iframe 事件监听器访问它
- python - 在 .CSV 数据导入中添加自动递增主键字段