如何从ssr数据初始化存储?

问题描述 投票:0回答:1

我正在开发一个组织成目录的 Next.js 项目,并且我还在实现 Redux 来进行客户端状态管理。我的页面位于应用程序目录 t 中。

此外,我正在服务器端获取一些数据,并希望使用此服务器端渲染的数据来初始化我的 Redux 存储。

这是我如何在主页组件中获取数据的示例:

Home.tsx

import { Box, Button, Typography } from "@mui/material";
import blogsecure from "./services/blogSecure";
import { BlogGetData } from "./models/BlogGet";

export const fetchData = async () => {
  const response = await blogsecure.get('/blogs/fetch_all'); //<- I want to initalize from this data

  if (response.status !== 200) {
    throw new Error("Failed to fetch API data");
  }
  return response.data;
};

const Home = async() => {
  const blogs: BlogGetData[] = await fetchData();
  return (
    <Box sx={{ position: 'relative', height: '100%' }}>
      <Button sx={{ position: 'absolute', bottom: 16, right: 16 }}>
        Create blog
      </Button>
      {blogs.map((blog) => <Typography>{blog.title}</Typography>)}
    </Box>
  );
}

export default Home;

这是我在 StoreProvider.tsx 和 store.ts 文件中处理 Redux 初始化的方式:

StoreProvider.tsx

import { useRef } from 'react';
import { Provider } from 'react-redux';
import { AppStore, makeStore } from '../lib/store';

const StoreProvider = ({ children }: { children: React.ReactNode }) => {
  const storeRef = useRef<AppStore>();
  if (!storeRef.current) {
    storeRef.current = makeStore();
  }

  return <Provider store={storeRef.current}>{children}</Provider>;
};

export default StoreProvider;

store.ts

import { configureStore } from '@reduxjs/toolkit';
import authReducer from './feature/auth/authSlice';
import blogsReducer from './feature/blogs/blogFetchSlice';
import userReducer from './feature/user/userSlice';

export const makeStore = () => {
  return configureStore({
    reducer: {
      auth: authReducer,
      user: userReducer,
      blogs: blogsReducer,
    }
  });
}

export type AppStore = ReturnType<typeof makeStore>;
export type RootState = ReturnType<AppStore['getState']>;
export type AppDispatch = AppStore['dispatch'];

在用于获取博客的 Redux 切片 (blogFetchSlice.tsx) 中,我定义初始状态和减速器如下:

博客FetchSlice.tsx

import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
import { BlogFetchAllState } from './types'; // Assuming you have defined types for state

export const fetchAllBlogs = createAsyncThunk(
  // my async logic here
);

const initialState: BlogFetchAllState = {
  blogs: null,<-- If I initialize here it is done from client side
  loading: false,
  error: null,
  current_blog: null
};

const blogFetchSlice = createSlice({
  name: 'blogFetchAll',
  initialState,
  reducers: {
    // Additional reducers if needed
  },
  extraReducers: (builder) => {
    // slice actions
  }
});

export default blogFetchSlice.reducer;

This setup initializes the Redux store with the server-side rendered data and provides a structure for managing your client-side state with Redux. If you need further assistance or clarification, feel free to ask!

I'm structuring a Next.js project with Redux for client-side state management. Each page resides in the app directory for better organization. I need guidance on initializing the Redux store with data fetched on the server side. Can you help me set up Redux initialization from server-side rendered data in this Next.js project?
next.js redux react-redux server-side-rendering redux-toolkit
1个回答
0
投票

目前这是不可能的,因为您的 Next.js App Router 应用程序同时在服务器和浏览器中运行 - 因此在服务器完成渲染之前您的商店已经在浏览器中创建。

React 需要添加一些原语来将数据注入到流中,然后才能使用 Redux 实现这一点。

© www.soinside.com 2019 - 2024. All rights reserved.