如何在Next.js的getInitialProps中通过next-redux-wrapper触发Redux action
问题根因
你遇到的dispatch调用失败、store返回undefined,核心是2个写法错误:
- next-redux-wrapper注入的store实例挂载在
ctx.store属性下,你直接从ctx解构dispatch、getState自然拿不到对应值 - 当前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
相关产品推荐
相关产品推荐

