nextjs集合redux中的HOC流程图理解

redux和nextjs

最近在学nextjs,学到了一个自己手写hoc去集合redux和nextjs的,通过代码不太好理解,所以就写成流程图去理解

维持客户端唯一个store

import store from 'stroe'

const isServer = typeof window === 'undefined'
const __NEXT_REDUX_STORE__ = '__NEXT_REDUX_STORE__'

function getOrCreateStore(initialState) {
    if(isServer) return initialState
    if(!window[__NEXT_REDUX_STORE__]) {
        window[__NEXT_REDUX_STORE__] =initialState
    }
     return  window[__NEXT_REDUX_STORE__] 
}

hoc

import React from 'react'
export default Comp =>{
    class Hoc extends React.Component{
        constuctor(props) {
            super(props)
            this.reduxStore = getOrCreateStore(props.initialReduxState
        }
        render({Component, pageProps, ...rest}) {
        // 这里可以对 pageprops进行处理
        return <Comp 
                   Component={Component} 
                   pageProps={pageProps} 
                   {...rest} 
            		reduxStore={this.reduxStore}   // reduxStore作为属性传给每一个页面
                />
        }
    }

    Hoc.getInitialProps = async (ctx) => {
        let appProps = {}
        if(typeof Comp.getInitialProps === 'function') {
            appProps = await Comp.getInitialProps(ctx)// 这个是组件的props
        }
        const reduxStore = getOrCreateStore()// 获取当前状态的redux的store
        return {
            ...appProps,
            initialReduxProps:reduxStore.getState()// 在每一个页面更新的时候 传一个initialReduxProps 作为获取到的redux的state
        }
    }
}

流程图

getInitialProps
HOC
每次路由都会执行
传给HOC组件
getOrCreateStore
作为props传给Com
HOC的参数是Com
getInitialProps
HOC的getInitialProps
ctx参数是继承于nextjs
获取全局的redux的store
转换成state 作为属性返回给HOC组件
appProps获取组件Com上的props
HOC
继承props和redux
render
判断全局 维持唯一个redux的store
完成继承和redux
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值