当我尝试在getServerSideProps中调度时,Redux Store不会更改
当我在调度后控制台日志存储时,我看到控制台中的更改,但当页面加载时,存储是空数组。。
为什么更改不会生效?
createSlice
import { createSlice } from "@reduxjs/toolkit";
import { Store } from "../../types/type";
const { actions, reducer } = createSlice({
name: "dashboard",
initialState: { users: [], roles: [], ads: [], category: [] },
reducers: {
SET_ROLES: (store, { payload }) => {
store.roles = payload;
return store;
},
SET_USERS: (store, { payload }) => {
store.users = payload;
return store;
},
SET_ADS: (store, { payload }) => {
store.ads = payload;
return store;
},
SET_CATEGORY: (store, { payload }) => {
store.category = payload;
return store;
},
},
});
// Selector
export const selectDashboard = (store: Store) => store.entities.dashboard;
export const { SET_ROLES, SET_ADS, SET_USERS, SET_CATEGORY } = actions;
export default reducer;
页面
export const getServerSideProps = wrapper.getServerSideProps(
(store) => async (context) => {
const { data: ads } = await axios.get(endPoint);
const { data: users } = await axios.get(endPoint);
const { data: roles } = await axios.get(endPoint);
const { data: categories } = await axios.get(endPoint);
console.log("Before DISPATCH", store.getState());
store.dispatch(SET_USERS(users));
store.dispatch(SET_ADS(ads));
store.dispatch(SET_CATEGORY(categories));
store.dispatch(SET_ROLES(roles));
console.log("After DISPATCH", store.getState()); // I Can See The Changes In Console
return {
props: {},
};
}
);
发生脱水时,服务器中设置的状态将被清除。您需要用客户端状态更新服务器状态。
const reducer = (
state: ReturnType<typeof combinedReducer> | undefined,
action: AnyAction
) => {
if (action.type === HYDRATE) {
const nextState = {
...state, // use previous state
...action.payload, // apply delta from hydration
};
return nextState;
} else {
return combinedReducer(state, action);
}
};
export const store = configureStore({
reducer,
devTools: process.env.NODE_ENV !== 'production',
middleware: (getDefaultMiddleware) =>
....