当我尝试在getServerSideProps中分派时,Redux存储区不会更改
当我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: {},
};
}
);
2条答案
按热度按时间siv3szwd1#
当发生数据删除时,服务器中设置的状态将被清除。您需要使用客户端状态更新服务器状态。
rsaldnfx2#
getServerSideProps
在呈现页面之前在服务器上执行。如果需要更新应用程序状态,则需要在组件本身上调度。
您可以做的是将加载的数据作为属性返回,在组件中检索它们,并在那里填充状态: