reactjs - 功能组件状态中的数组值未更新
问题描述
我已经设置了一个 useState 挂钩,如下所示。
const [products, setProducts] = useState([
{
id: 1,
qty: 0,
},
{
id: 2,
qty: 0,
}
]);
我有一个 TouchOpacity 组件,它在按下时会触发以下功能。
const _onPress = () => {
const productArr = products;
productArr[0].qty = value;
setProducts(productArr);
};
预期结果是 id 为 1 的产品必须将数量增加到 1,但这不会发生。
当我对来自状态的产品使用扩展运算符时,它按预期工作。
const _onPress = () => {
const productArr = [...products];
productArr[0].qty = value;
setProducts(productArr);
};
这是什么原因?
解决方案
请注意,即使使用扩展运算符,在您的两个示例中,您都在改变状态。
如果您需要在状态或嵌套结构中使用数组,我强烈建议您尝试一个库,例如immer
它可以简化事情,比重新创建对象更有效,并且总体上会给您一个很好的不改变状态的概念:
import produce from "immer";
const [products, setProducts] = useState([
{
id: 1,
qty: 0,
},
{
id: 2,
qty: 0,
}
]);
const _onPress = () => {
setProducts(
produce(products, draft => draft[0].qty = value)
);
}
推荐阅读
- scala - 当T扩展A时,如何将classOf [T]传递给接受A的方法?
- c# - C# Winforms Listbox 按日期过滤 Datagridview
- python - 使用 Anaconda 从 Python 2 升级到 Python 3
- ruby-on-rails - 无法在 Rails 应用程序中更改 Shrine Amazon S3 前缀
- multiprocessing - 进程池完成后的 Python Futures 错误 - atexit._run_exitfuncs
- python - 从客户端打开到 SQL Server 数据库的连接数是否有限制?
- php - 如何在存储在二维数组中的生成地形中查找结构(包含 X 个单元格)?
- vue.js - 移动设备上的 Nuxt 静态生成不匹配
- javascript - 如何将 Kafkajs 与 Socket.io 连接
- arrays - Dafny 中的高阶计数 (P)