首页 > 解决方案 > 从 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;

如果您需要显示更多代码,请告诉我。非常感谢您的帮助!谢谢

当前项目值 在此处输入图像描述

有时它会给出如下错误:

Possible Unhandled Promise Rejection (id: 0):
TypeError: Cannot assign to read only property 'quantity' of object '#<Object>'

标签: react-nativereact-reduxreact-hooks

解决方案


您有一个对象数组,因此您需要执行以下操作

rows[currentItemIndex].quantity = currentItemValues.quantity;

推荐阅读