目前要做 Next js 和 Redux 与 next-redux-wrapper 连接。
问题是代码不像我想的那样工作..
我正在尝试制作基本计数器
我所期望的
在 getServerSideProps 期间,调度 add(3) 将 3 添加到 initialState 0,
所以在 SSR 之后,预期的初始值为 3
但实际上是 0。
这是我的代码
索引.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 包装了应用程序组件。
有什么我认为不正确的吗??