[英]Why State won't Change When I try to dispatch in getServerSideProps? Redux-Next-Wrapper
當我嘗試在 getServerSideProps 中調度時,Redux 存儲不會改變
當我在 Dispatch 后 Console.log 商店時,我看到控制台中的更改,但是當頁面加載時,商店是空數組..
為什么更改不會生效?
創建切片
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: {},
};
}
);
getServerSideProps
在服務器上執行,先於渲染頁面。
如果您需要更新您的應用程序 state,您需要在組件本身上進行調度。
您可以做的是將加載的數據作為道具返回,在組件中檢索它們,並在那里填充 state:
const YourComponent = ({ ads, users, roles, categories }) => {
useEffect(() => {
// Populate application state
store.dispatch(SET_USERS(users));
store.dispatch(SET_ADS(ads));
store.dispatch(SET_CATEGORY(categories));
store.dispatch(SET_ROLES(roles));
}, [])
...
}
export const getServerSideProps = 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);
return {
props: {
ads,
users,
roles,
categories,
},
};
};
當脫水發生時,服務器中設置的 state 將被清除。 您需要使用客戶端 state 更新服務器 state。
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) =>
....
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.