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

如何在Next.js的getInitialProps中通过next-redux-wrapper触发Redux action

问题根因

你遇到的dispatch调用失败、store返回undefined,核心是2个写法错误:

  1. next-redux-wrapper注入的store实例挂载在ctx.store属性下,你直接从ctx解构dispatch、getState自然拿不到对应值
  2. 当前store创建时没有配置异步中间件,如果你用的是异步action拉取artPieces数据,原生createStore无法处理函数类型的action

另外你代码中还存在getInitialProps内引用未定义变量data的低级错误。


修复步骤

1. 调整store.js支持异步action

先安装redux-thunk依赖,再调整store创建逻辑,同时补充artPieces相关的reducer处理:

import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import { createWrapper, HYDRATE } from 'next-redux-wrapper';

const reducer = (state = { tick: 'init', artPieces: [] }, action) => {
    switch (action.type) {
        case HYDRATE:
            return { ...state, ...action.payload };
        case 'TICK':
            return { ...state, tick: action.payload };
        // 匹配你getArtPieces异步请求成功后触发的action
        case 'SET_ART_PIECES':
            return { ...state, artPieces: action.payload };
        default:
            return state;
    }
}; 

const makeStore = (context) => createStore(reducer, applyMiddleware(thunk));
export const wrapper = createWrapper(makeStore, { debug: true });

2. 修正Art页面的getInitialProps写法

从ctx.store取dispatch和getState方法,删除未定义变量的引用:

import React from 'react';
import { ArtPiecesContainer } from './../components/ArtPiecesContainer';
import { getArtPieces } from '../reducers';

const Art = ({ data, error }) => {
    return (
        <>
            <ArtPiecesContainer artPieces={data?.artPieces || []} />
        </>
    );
};

export default Art;

Art.getInitialProps = async (ctx) => {
    const { dispatch, getState } = ctx.store;
    await dispatch(getArtPieces());

    const fullState = getState();
    console.log('DATA FROM GETARTPIECES', fullState.artPieces);

    return { data: fullState };
};

3. 确认异步action写法正确

你的getArtPieces需要符合redux-thunk的规范,示例写法参考:

export const getArtPieces = () => async (dispatch) => {
  // 替换为你的实际接口地址
  const res = await axios.get('/api/art-pieces');
  dispatch({
    type: 'SET_ART_PIECES',
    payload: res.data
  })
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 15:09:02