javascript - ReactJS 不保存对象
问题描述
我目前在 React 中遇到一个奇怪的问题,即数组中更改的对象无法保存。
changeQuantity(Product, Quantity) {
let index = this.state.products.findIndex(p => p === Product);
Product.Amount = Quantity;
let productarray = this.state.products;
productarray[index] = Product;
console.log(index);
console.log(productarray[index]);
console.log(productarray);
this.setState({
products: productarray
})
}
index
= 0
productarray[index]
= 有正确的Amount
productarray
= 有错误Amount
(仍然为零,无论我输入哪个数字Quantity
关于为什么它不能正确保存,我在这里有什么遗漏吗?
解决方案
尝试创建一个新数组,这就是 react 判断对象是否更改的方式。
oldArray[index] = anotherObject
const newArray = [...oldArray]
setState{ products: newArray }
推荐阅读
- csv - 无法 CSV 使用 tf.compat.v1.keras.utils.get_file 在 Colab 中加载文件
- reactjs - Filepond React:Revert 调用不包含任何 id(已解决)
- python-3.x - Pytest Flask Application AttributeError:模块'src.api'没有属性'test_client'
- java - Spring MVC - JSP 中的打印表格
- python - 需要在熊猫数据框中按月过滤日期
- firebase - Firebase 突然给出访问 Firebase 存储的权限错误
- c# - HttpRequestException 显式错误处理
- sql - java.sql.SQLSyntaxErrorException: ORA-00936: 缺少表达式,即使什么都没有
- c - 如何修复连接到 C 中服务器的方法?
- apache-kafka - Kafka MirrorMaker 中的生产者线程数