react-native - 从 useEffect 挂钩调度时,Redux 数组状态未更新
问题描述
我正在尝试在单击按钮时使用钩子更新 react-redux 中的状态。
单击按钮时,它会更新 ordersArray,我需要在 redux 状态下更新该数组。
目前我正在使用下面的代码,我的状态数组保持不变,没有任何变化。
useEffect(() => {
if (!_.isEmpty(tempOrders)) {
// console.log('tempOrderstempOrders', tempOrders);
dispatch(storeCartOrders(tempOrders));
}
}, [dispatch, tempOrders]);
cartOrderSlice.js
import {createSlice, createAsyncThunk} from '@reduxjs/toolkit';
const slice = createSlice({
name: 'cartOrder',
initialState: {
cartOrders: [],
},
reducers: {
// Redux Toolkit allows us to write "mutating" logic in reducers. It
// doesn't actually mutate the state because it uses the immer library,
// which detects changes to a "draft state" and produces a brand new
// immutable state based off those changes
storeCartOrders: (state, action) => {
console.log('action.payload', action.payload) // <-- this payload always has old values
state.cartOrders = action.payload;
},
},
});
export const {storeCartOrders} = slice.actions;
export default slice.reducer;
useEffect
单击按钮时调用以下内容下面的 useEffect 将
setTempOrders
依次调用带有函数的useEffect
钩子dispath
useEffect(() => { const updateOrders = async () => { let rows = [...tempOrders]; if (currentItemValues) { const currentItemIndex = rows.findIndex( (row) => row.id === currentItemValues.id, ); if (currentItemIndex >= 0) { if (currentItemValues.quantity === 0) { rows.splice(currentItemIndex, 1); } else { rows[currentItemIndex]['quantity'] = currentItemValues.quantity; } } } // console.log('rowsrowsrows', rows); // rows[currentItemIndex]['quantity'] is not being changed at all. // and that's why storage and setTempOrders won't change the data. setTempOrders(rows); await setLocalCartItems('cart', rows); }; if (!_.isEmpty(tempOrders)) { updateOrders(); } }, [currentItemValues, toggle]);
如果您需要显示更多代码,请告诉我。非常感谢您的帮助!谢谢
有时它会给出如下错误:
Possible Unhandled Promise Rejection (id: 0):
TypeError: Cannot assign to read only property 'quantity' of object '#<Object>'
解决方案
您有一个对象数组,因此您需要执行以下操作
rows[currentItemIndex].quantity = currentItemValues.quantity;
推荐阅读
- php - 如何在 Behat 中启用 Mink 扩展
- python - Python - CSV 文件使用数据流模板进行 Dict
- c++ - 如何通过函数参数返回指向不规则数组的指针?
- php - 在 WordPress 中通过 PHP 显示兄弟页面
- angular - 我想以角度在两个单独的循环中添加序列号
- python - python pandas数组合并
- excel - Excel VLOOKUP/INDEX 根据值多次
- apache-spark - 作业的 TaskCommitDenied(驱动程序拒绝任务提交):
分割: ,尝试次数: - python - 排序链接不会在 django-tables2 中保留页面锚点
- php - laravel find() 返回空刀片文件时返回错误