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
}
}
}