Next.js中next-redux-wrapper数据同步问题求助:initialState无数据
Next.js + next-redux-wrapper 状态同步问题
在Next.js中使用next-redux-wrapper的initialStateFromGSPorGSSR实现Redux服务端渲染时,遇到initialState为undefined但initialStateFromGSPorGSSR存在有效数据的问题,排查后怀疑是reducer中的HYDRATE逻辑出错,但无法定位具体问题。
浏览器控制台日志
4. withRedux(MyApp) created new store with {initialState: undefined, initialStateFromGSPorGSSR: {…}} initialState : undefined initialStateFromGSPorGSSR : {videosSlice: {…}} [[Prototype]] : Object
VSCode终端日志
1. getProps created store with state { videosSlice: { items: [] } } 3. getProps after dispatches has store state { videosSlice: { items: [ [Object], [Object], [Object], [Object], [Object], [Object], [Object], [Object], [Object], ] } } 4. withRedux(MyApp) created new store with { initialState: undefined, initialStateFromGSPorGSSR: { videosSlice: { items: [Array] } }
相关代码
store.js
import { configureStore, combineReducers } from "@reduxjs/toolkit"; import videosSlice from "./video-slice"; import { HYDRATE, createWrapper } from "next-redux-wrapper"; const combinedReducer = combineReducers({ videosSlice, }); const masterReducer = (state, action) => { if (action.type === HYDRATE) { const nextState = { ...state, ...action.payload.data, }; return nextState; } else { return combinedReducer(state, action); } }; export const makeStore = () => { return configureStore({ reducer: masterReducer, }); }; export const wrapper = createWrapper(makeStore, { debug: true });
video-slice.js
import { createSlice } from "@reduxjs/toolkit"; const videosSlice = createSlice({ name: "videos", initialState: { items: [], }, reducers: { getAllVideos(state, action) { state.items = action.payload.data; }, }, }); export const { getAllVideos } = videosSlice.actions; export default videosSlice.reducer;
page.js
import { wrapper } from "../redux/index"; import { getAllVideos } from "../redux/video-slice"; import { useSelector } from "react-redux"; import { Fragment } from "react"; import Head from "next/head"; import Header from "./Header"; import VideosList from "./VideosList"; export default function Home(props) { const videos = useSelector((state) => state.videosSlice.items); return ( <Fragment> <Head> <title>My App</title> <link rel="icon" href="/favicon.ico" /> </Head> <Header /> <VideosList videos={videos} /> </Fragment> ); } export const getServerSideProps = wrapper.getServerSideProps( (store) => async () => { const res = await fetch("https://dummyjson.com/products"); const { products: data } = await res.json(); store.dispatch( getAllVideos({ data: data || [], }) ); } );
备注:数据获取环节无错误,问题大概率出在HYDRATE或reducer逻辑上。寻求熟悉Next.js中Redux使用的开发者帮助,可通过Discord联系:DeadhorAlive#6795。
内容的提问来源于stack exchange,提问作者eErgun
相关产品推荐
相关产品推荐

