【问题标题】:next-redux-wrapper server not sync with client?next-redux-wrapper 服务器不与客户端同步?
【发布时间】:2021-11-18 07:02:45
【问题描述】:

目前要做 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 包装了应用程序组件。

有什么我认为不正确的地方吗??

【问题讨论】:

    标签: redux next.js next-redux-wrapper


    【解决方案1】:

    我找到了原因....

    水合物部分应该是

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-21
      • 1970-01-01
      • 2013-11-16
      • 2018-01-11
      相关资源
      最近更新 更多