【发布时间】:2021-10-04 21:21:15
【问题描述】:
我正在尝试迁移到 redux 工具包,但遇到了一个问题。
这是一个简单的计数器切片示例。
import { createSlice } from "@reduxjs/toolkit";
const initialState = {
value: 0,
};
export const counterSlice = createSlice({
name: "counter",
initialState,
reducers: {
increment: (state) => {
state.value += 1;
},
decrement: (state) => {
state.value -= 1;
},
},
});
export const { increment, decrement } = counterSlice.actions;
export default counterSlice.reducer;
这是一个使用 configureStore 创建的商店。
import { configureStore } from "@reduxjs/toolkit";
import counterReducer from "./slice";
export const store = configureStore({
reducer: {
counter: counterReducer,
// later, many other reducers will be added here.
},
});
还有什么问题。
但是如果我引入preloadedState,那就有问题了。
const store = configureStore({
reducer: counterReducer,
preloadedState: {
counter: {
value: 10
}
},
});
如果我像下面这样记录存储的状态,它会按预期记录。
// without using preloadedState, it results to {counter: {value: 0}}
console.log(store.getState())
// with using preloadedState, it results to {counter: {value: 10}}
console.log(store.getState())
但是在使用 slice reducer 的时候会出现一个问题,因为 slice reducer 使用的是自己的 state。
...
reducers: {
increment: (state) => {
state.value += 1; // not work anymore if using preloadedState. we have to use state.counter.value instead.
},
decrement: (state) => {
state.value -= 1; // not work anymore if using preloadedState. we have to use state.counter.value instead.
},
},
...
我们必须使用,
...
reducers: {
increment: (state) => {
state.counter.value += 1;
},
decrement: (state) => {
state.counter.value -= 1;
},
},
...
所以问题是,我们是否必须添加条件语句,根据我们是否使用 preloadedState 来分离 slice reducer 内部的逻辑?
只要提供了 preloadedState,如果 slice reducer 使用 preloadedState 而不是使用它自己的状态,那就太好了。有没有更好的方法?
谢谢。
【问题讨论】:
标签: redux redux-toolkit