从useEffect钩子分发时,Redux数组状态未更新

时间:2020-11-02 03:36:39

标签: react-native react-redux react-hooks

我试图通过单击钩子使用钩子来更新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]);
    

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

currentItemValues enter image description here

有时它会给出如下错误:

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

1 个答案:

答案 0 :(得分:0)

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

rows[currentItemIndex].quantity = currentItemValues.quantity;