initialReduxState 的作用
来源:5-9 nextjs集成redux(2)

宝求cross
2020-07-22
先打出来全部代码
import React from 'react'
import createSore from '../store/store'
const isServer = typeof window === 'undefined'
const __NEXT_REUDX_STORE__ = '__NEXT_REUDX_STORE__'
function getOrCreateStore(initialState) {
if (isServer) {
return createSore(initialState)
}
if (!window[__NEXT_REUDX_STORE__]) {
window[__NEXT_REUDX_STORE__] = createSore(initialState)
}
return window[__NEXT_REUDX_STORE__]
}
export default Comp => {
class WithReduxApp extends React.Component {
constructor(props) {
super(props)
this.reduxStore = getOrCreateStore(props.initialReduxState)
}
render() {
// const name = name + '123'
const { Component, pageProps, ...rest } = this.props
// console.log(Component, pageProps)
if (pageProps) {
pageProps.test = '123'
}
return (
<Comp
Component={Component}
pageProps={pageProps}
{...rest}
reduxStore={this.reduxStore}
/>
)
}
}
WithReduxApp.getInitialProps = async ctx => {
const reduxStore = getOrCreateStore()
ctx.reduxStore = reduxStore
let appProps = {}
if (typeof Comp.getInitialProps === 'function') {
appProps = await Comp.getInitialProps(ctx)
}
return {
...appProps,
initialReduxState: reduxStore.getState(),
}
}
return WithReduxApp
}
在getInitialProps方法中返回了 { ...appProps, initialReduxState: reduxStore.getState(), }
所以 render()方法中`const { Component, pageProps, ...rest } = this.props`时,{...rest}如果扩展开的话应该是包含initialReduxState,再看以下render中的return内容
return (
<Comp
Component={Component}
pageProps={pageProps}
{...rest}
reduxStore={this.reduxStore}
/>
即传递了reduxStore,还传递了包含initialReduxState的{…rest}。这里不太明白的是,Comp组件可以获得reduxStore, 如果想查看store中state的话,可以调用store.getStore(). 那么还有必要在getInitialProps中传入initialReduxState吗?这个initialReduxState被传递进去的作用是什么呢?
写回答
1回答
-
Jokcy
2020-07-26
有,因为getInitialProps里面返回的initialReduxState是会让nextjs帮我们处理服务端数据在客户端复用的。
00
全栈进阶课程 React16.8+Next.js+Koa2一步到位开发Github
学习React/Next.js服务端渲染SSR同构设计方案,理解OAuth登录体系的实现原理
651 学习 · 311 问题
相似问题