React SSR场景下导出的getServerSideProps用于connect报错如何解决
核心问题
你现在的错误根源是混淆了getServerSideProps和connect第一个参数mapStateToProps的作用与返回结构要求,两个函数完全不通用,不能直接把getServerSideProps作为参数传给connect:
getServerSideProps是Next.js服务端渲染专用的导出函数,要求返回格式为{ props: 要传递给组件的属性对象 }connect的第一个入参是mapStateToProps,要求直接返回要注入给组件的属性对象,不能嵌套props字段
解决方案
拆分两个独立函数分别处理服务端导出和Redux状态映射即可:
- 保留
export function getServerSideProps供Next.js服务端渲染调用 - 单独定义
mapStateToProps函数传给connect使用
修改后完整代码参考:
import { connect } from 'react-redux' // 注意:服务端不能直接使用客户端全局store,需要每次请求初始化独立store实例,这里根据你自己的项目store逻辑调整 import { initializeStore } from '你的store初始化文件路径' function Home ({ products, loading }) { return ( <Component products={products} loading={loading} /> ) } // 专门用于服务端渲染导出的函数 export function getServerSideProps() { const store = initializeStore() // 服务端每次请求初始化新store,避免多请求状态污染 const state = store.getState() const { products, loading } = state.productList console.log('serverProps products:') console.log(products) return {props: {products, loading}} } // 专门用于connect的mapStateToProps函数 const mapStateToProps = (state) => { // 客户端需要从Redux同步的状态在这里定义,不需要可以返回空对象 return {} } export default connect(mapStateToProps)(Home)
额外说明
如果你通过getServerSideProps已经把需要的products和loading传递给了组件,客户端不需要再从Redux同步这两个字段的话,甚至可以直接去掉connect的第一个参数,写为connect()(Home)即可,组件可以直接拿到getServerSideProps返回的属性。
内容的提问来源于stack exchange,提问作者shanksu 218
相关产品推荐
相关产品推荐

