目前要使用next- Redux -wrapper连接Next js和redux。
问题是代码并不像我想的那样工作。
我在试着做基本的计数器
我所期望的
在getServerSideProps期间,调度将3加到initialState 0的add(3),
所以在SSR之后,期望的初始值是3
但它实际上是0。
以下是我的代码
Index.tsx
export const getServerSideProps = wrapper.getServerSideProps(
(store) => async () => {
store.dispatch(add(3));
return {
props: {},
};
}
);
const index = (props: any) => {
const count = useSelector((state: AppState) => state.counter.count);
const dispatch = useDispatch();
return (
<>
<div>{count}</div>
<button onClick={() => dispatch(add(1))}>+</button>
<button onClick={() => dispatch(deleter(2))}>-</button>
</>
);
};store.ts
export const counterSlice = createSlice({
name: 'counter',
initialState: { count: 0 },
reducers: {
add: (state, action) => {
state.count += action.payload;
},
deleter: (state, action) => {
state.count -= action.payload;
},
},
extraReducers: {
[HYDRATE]: (state, action) => {
console.log('HYDRATE', state, action.payload);
const nextState = { ...state, ...action.payload };
return { ...nextState };
},
},
});
const makeStore = () =>
configureStore({
reducer: {
[counterSlice.name]: counterSlice.reducer,
},
devTools: true,
});
export type AppStore = ReturnType<typeof makeStore>;
export const wrapper = createWrapper<AppStore>(makeStore);我已经删除了看起来不必要的(一些类型...)和
在_app.tsx中,我确实用WithRedux包装了应用程序组件。
我有没有想错的地方??
发布于 2021-09-25 08:31:07
我找到原因了..。
水合物部分应该是
extraReducers: {
[HYDRATE]: (state, action) => {
console.log('HYDRATE', state, action.payload);
const nextState = { ...state, ...action.payload.counter };
return nextState;
},
},https://stackoverflow.com/questions/69324423
复制相似问题