You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决next-redux-wrapper中客户端响应出现重复initialState的问题?

修复方案

1. 正确返回pageProps

你的App.getInitialProps回调函数未返回任何值,导致next-redux-wrapper默认将store的state作为initialState同时注入到App的外层props和pageProps内部,造成重复。需要在回调末尾明确返回包含pageProps的对象:

App.getInitialProps = wrapper.getInitialPageProps((store) => async (context) => {
    if (context.req) {
        const dataAuth = await fetchAuth(context);
        if (dataAuth) store.dispatch(authSlice.actions.setAuth(dataAuth));
        else store.dispatch(authSlice.actions.resetAuth());
    }
    // 获取页面自身的pageProps(如果页面组件有定义getInitialProps)
    const pageProps = await (Component.getInitialProps?.(context) || {});
    // 仅返回pageProps,避免重复注入initialState
    return { pageProps };
});

2. 检查Wrapper配置

确保createWrapper的配置没有手动重复处理initialState的逻辑,标准配置示例:

import { createWrapper } from 'next-redux-wrapper';
import { configureStore } from '@reduxjs/toolkit';
import authSlice from './slices/authSlice';

const makeStore = () => configureStore({
    reducer: {
        auth: authSlice.reducer,
    },
});

export const wrapper = createWrapper(makeStore);

3. 避免将initialState传递给子组件

pageProps中的initialState是给redux store初始化用的,不需要传递给子组件。子组件需要的数据应通过useSelector从store中获取,而非props。如果需要传递其他props,手动筛选字段:

function App({ Component, pageProps }) {
    // 移除pageProps中的initialState,只传递业务需要的props
    const { initialState, ...restProps } = pageProps;
    return (
        <Layout>
           <Component {...restProps} />
        </Layout>
    );
}

问题根源

next-redux-wrapper的getInitialPageProps默认会把服务器端store的state序列化后,作为initialState放入pageProps供客户端初始化store。当回调函数未正确返回pageProps时,会触发重复注入逻辑,导致initialState同时出现在pageProps外部和内部。


内容的提问来源于stack exchange,提问作者Epple

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 22:15:29