Redux toolkit Redux Toolkit-从一个片段到另一个片段的操作
orderSlice中有一个操作(addOrder) orderSlice.jsRedux toolkit Redux Toolkit-从一个片段到另一个片段的操作,redux-toolkit,Redux Toolkit,orderSlice中有一个操作(addOrder) orderSlice.js import { createSlice } from '@reduxjs/toolkit'; const initialState = { orders: [] }; const ordersSlice = createSlice({ name: 'orders', initialState, reducers: { addOrder: { reducer: (state,
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恢复到初始状态。一些谷歌建议我应该使用ExtraReducer,但我真的不明白它的语法。参见下文(extrareducers中的无效代码)
cartSlice
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
函数执行以下操作。第一个是action creator,第二个是case reducer。因此,在addOrder
之后需要一个逗号
extraReducers: (builder) => {
builder.addCase(addOrder, (state) => {
return initialState;
});
}
伟大的很好。