Redux 工具包 - 从一个切片到另一个切片的动作

Redux Toolkit - action from one slice to be caught in another slice

orderSlice 中有一个操作 (addOrder)

orderSlice.js

import { createSlice } from '@reduxjs/toolkit';
const initialState = {
  orders: []
};

const ordersSlice = createSlice({
  name: 'orders',
  initialState,
  reducers: {
    addOrder: {
      reducer: (state, action) => {
        state.orders.push(action.payload)
      },
      prepare: (orderItems, orderTotal) => {
        const orderDate = new Date().toDateString();
        return { payload: { orderDate, orderItems: orderItems, orderTotal: orderTotal }}
      }
    }
  }
})

export const { addOrder } = ordersSlice.actions;
export default ordersSlice.reducer;

我希望它也能影响另一个切片 (cartSlice) 中的状态。一旦 'addOrder' 被触发,它也应该将 cartReducer 带到它的初始状态。一些谷歌搜索建议我应该为此使用 extrareducers 但我真的没有得到它的语法。见下文(extrareducers 中的无效代码)

购物车切片

import { createSlice } from '@reduxjs/toolkit';
import { addOrder } from './ordersSlice';

const initialState = {
  items: {},
  totalAmount: 0
};

const cartSlice = createSlice({
    name: 'cart',
    initialState: initialState,
    reducers: {
      addToCart: (state, action) => {
        // p = product to be added or amended
        const p = action.payload;
        if (state.items[p.id]) {
          // already exists
          state.items[p.id].quantity += 1;
          state.items[p.id].sum += p.price;
          state.totalAmount += p.price;
        } else {
          state.items[p.id] = { price: p.price, quantity: 1, title: p.title, sum: p.price};
          state.totalAmount += p.price;
        }
      },
      removeFromCart: (state, action) => {
        console.log('remove from cart');
        console.log(action.payload);
        const currentQuantity = state.items[action.payload].quantity;
        console.log(currentQuantity);
        if (currentQuantity > 1) {
          state.items[action.payload].quantity -= 1;
          state.items[action.payload].sum -= state.items[action.payload].price;
          state.totalAmount -= state.items[action.payload].price;
        } else {
          state.totalAmount -= state.items[action.payload].price;
          delete state.items[action.payload];
        }
      }
    },
    extraReducers: (builder) => {
      builder
        .addCase(addOrder(state) => {
          return initialState;
      })
    }
  });

export const { addToCart, removeFromCart } = cartSlice.actions;
export default cartSlice.reducer;

你就快完成了! builder.addCase 函数采用 two arguments。第一个是 action creator,第二个是 case reducer。所以你需要在 addOrder.

之后加一个逗号
extraReducers: (builder) => {
  builder.addCase(addOrder, (state) => {
    return initialState;
  });
}