【问题标题】:Redux array state is not updating when dispatching from useEffect hook从 useEffect 挂钩调度时,Redux 数组状态未更新
【发布时间】:2021-02-14 18:03:17
【问题描述】:

我正在尝试使用钩子更新 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 依次调用带有 dispath 函数的 useEffect 钩子

      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

有时它会给出如下错误:

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

【问题讨论】:

  • 你能显示你的按钮点击代码吗?如果你有一个按钮点击,当你可以在点击时调用调度时为什么需要使用 useEffect ?
  • 我已经更新了问题和标题,它是从 useEffect 调用的。很抱歉造成混乱。
  • 调用 setTempOrders(rows) 之前的当前值是多少?
  • currentItemValues 的值。
  • 我更新了问题。实际上我意识到它可能与调度功能不更新状态无关。它更多的是一个不更新值 rows[currentItemIndex]['quantity'] = currentItemValues.quantity; 的数组请查看图像并知道数量为 3,但在行更新后没有更改。

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


【解决方案1】:

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

rows[currentItemIndex].quantity = currentItemValues.quantity;

【讨论】: