next-redux-wrapper服务器与客户端不同步?

nhhxz33t  于 2023-04-30  发布在  其他
关注(0)|答案(1)|浏览(133)

目前要做Next js和Redux连接,需要使用next-redux-wrapper。
问题是代码不像我想的那样工作。.
我在试着做基本的计数器
我所期望的
在getServerSideProps期间,调度add(3),它将3添加到initialState 0,
所以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 Package 了应用组件。
有什么我想错了吗??

lawou6xi

lawou6xi1#

我找到原因了...
水合物部分应为

extraReducers: {
        [HYDRATE]: (state, action) => {
            console.log('HYDRATE', state, action.payload);
            const nextState = { ...state, ...action.payload.counter };

            return nextState;
        },
    },

相关问题