• next.js 集成redux


    在使用next.js 我们有一部分数据,是需要同步到服务端环境的,在页面到达浏览器之前,redux就应该填充一部分数据

    其他框架参考, nuxt.js vuex 某个只在服务端初始化执行的action函数

    首先建立仓库文件 store/index.js

    1. import { combineReducers, createStore } from 'redux';
    2. import { composeWithDevTools } from 'redux-devtools-extension/developmentOnly';
    3. import user from './reducers/user'
    4. import config from './reducers/config'
    5. import anchor from './reducers/anchor';
    6. import router from './reducers/router';
    7. //每个redux已经单独分开,如果在初始化需要单独初始化某个模块的数据,需要这样合并,详情看redux文档
    8. const combined = (state = {}, action) => {
    9.   return {
    10.     user: user(state?.user, action),
    11.     config: config(state?.config, action),
    12.     router: router(state?.router, action),
    13.     anchor: anchor(state?.anchor, action)
    14.   };
    15. }
    16. //这里为了在服务端创建时,初始化一遍redux
    17. const createNextStore = (init) => createStore(combined, init, composeWithDevTools());
    18. export default createNextStore

    建立withRedux 用于结合redux和app

    1. import createNextStore from "./index";
    2. import { getUserInfo, getAnchorPage } from '@/service/live';
    3. import dayJs from 'dayjs';
    4. import React from 'react'
    5. const __NEXT_REDUX_STORE = "__NEXT_REDUX_STORE"; //定义个变量用来查看客户端是否存在store
    6. //根据不同场景进行创建或者返回现有store
    7. function getOrCreateStore (initialState) {
    8.   const isServer = typeof window === "undefined";
    9.   if (isServer) {
    10.     // 服务端
    11.     // 返回新的store
    12.     return createNextStore(initialState);
    13.   }
    14.   if (!window[__NEXT_REDUX_STORE]) {
    15.     // console.log('XXX')
    16.     // 是客户端客户端没有store create
    17.     window[__NEXT_REDUX_STORE] = createNextStore(initialState);
    18.   }
    19.   return window[__NEXT_REDUX_STORE];
    20. }
    21. const withRedux = (Comp) => {
    22.   // 高阶组件,让每个app都经历高阶组件进行处理集成redux
    23.   return class HocReducerComp extends React.Component {
    24.     constructor(props) {
    25.       super(props);
    26.       this.ReduxStore = getOrCreateStore(props.initialState);
    27.     }
    28.     static async getInitialProps (ctx) {
    29.       let user = {
    30.       }
    31.       let anchor = {
    32.       }
    33. //尝试在服务端先获取用户信息,在注入到客户端
    34.       try {
    35.         //尝试获取用户信息
    36.         if (ctx.ctx.req?.cookies['app-access-token']) {
    37.           const code = ctx.ctx.req.cookies['app-access-token'] || ""
    38.           user.info = await getUserInfo({
    39.             headers: {
    40.               "app-access-token": code
    41.             }
    42.           })
    43.           user.info['app_access_token'] = code
    44.           user.info = { ...user?.info, registerDay: dayJs().diff(dayJs(user?.info?.createTime), 'day') || 0, }
    45.           if (user?.info?.roomId) {
    46.             const c = await getAnchorPage({
    47.               headers: {
    48.                 "app-access-token": code
    49.               }
    50.             })
    51.             const { host = {}, ...other } = c;
    52.             anchor.anchorInfo = { ...host, ...other }
    53.           }
    54.         }
    55.       } catch (error) {
    56.         console.log(error)
    57.       }
    58.       const MyStore = getOrCreateStore({ anchor, user });
    59.       /* 利用ctx把store传入App,在App中进行store的初始化 */
    60.       ctx.ReduxStore = MyStore;
    61.       let appProps = {};
    62.       if (typeof Comp.getInitialProps === 'function') {
    63.         appProps = await Comp.getInitialProps(ctx);
    64.       }
    65.       // 这里都是在服务端重新注入数据
    66.       return { ...appProps, initialState: MyStore.getState() };
    67.     }
    68.     render () {
    69.       return <Comp {...this.props} ReduxStore={this.ReduxStore} />;
    70.     }
    71.   }
    72. };
    73. export default withRedux;

    _app.js 合并

    1. import 'normalize.css';
    2. import '../styles/main.scss';
    3. import { Provider } from "react-redux";
    4. import withRedux from "@/store/withRedux"
    5. import App from 'next/app'
    6. function nextApp ({ Component, pageProps, ReduxStore }) {
    7.   return (
    8.     <Provider store={ReduxStore}>
    9.       <Component {...pageProps} />
    10.     Provider>
    11.   )
    12. }
    13. nextApp.getInitialProps = async (ctx) => {
    14.   const appProps = await App.getInitialProps(ctx);
    15. //ctx.ReduxStore
    16.   return { ...appProps };
    17. };
    18. export default withRedux(nextApp)

  • 相关阅读:
    vtkjs中Sample Distance功能
    【剑指offer】数据结构——数
    【Git系列】02_Git分支
    朴素贝叶斯分类算法流程——python
    appium+python自动化测试
    vue-router的安装和使用
    Ubuntu20.04搭建web服务器
    华为设备配置VRRP负载分担
    #FreeRTOS延时函数
    JVM 重要知识梳理
  • 原文地址:https://blog.csdn.net/u013611033/article/details/126156873