首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >next-redux-wrapper服务器是否与客户端不同步?

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

Stack Overflow用户
提问于 2021-09-25 08:28:22
回答 1查看 47关注 0票数 0

目前要使用next- Redux -wrapper连接Next js和redux。

问题是代码并不像我想的那样工作。

我在试着做基本的计数器

我所期望的

在getServerSideProps期间,调度将3加到initialState 0的add(3),

所以在SSR之后,期望的初始值是3

但它实际上是0。

以下是我的代码

Index.tsx

代码语言:javascript
复制
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

代码语言:javascript
复制
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包装了应用程序组件。

我有没有想错的地方??

EN

回答 1

Stack Overflow用户

发布于 2021-09-25 08:31:07

我找到原因了..。

水合物部分应该是

代码语言:javascript
复制
extraReducers: {
        [HYDRATE]: (state, action) => {
            console.log('HYDRATE', state, action.payload);
            const nextState = { ...state, ...action.payload.counter };

            return nextState;
        },
    },
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69324423

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档