使用next.js时出现服务器错误,错误:找不到react-redux上下文值;请确保组件包装在<Provider>中

安详

我使用next.js ssr,并且出现服务器错误,我的代码如下:错误:找不到react-redux上下文值;请确保将组件包装在

我想我的代码会使用错误,但是我不知道如何解决?

在我的Header.jsx中:

import React from 'react'
import {
  useSelector,
} from 'react-redux'

const Header = props => {
  const user = useSelector(state => state.getIn(['header', 'user']).toJS())
  return (
    <div>...</div>
  )
}
export default Header

在我的_app.jsx中:

import App, { Container } from 'next/app'
import 'antd/dist/antd.css'
import React from 'react'
import { Provider } from 'react-redux'
import Layout from '../components/Layout'
import withRedux from '../lib/with-redux-app'

class MyApp extends App {

  static async getInitialProps(ctx) {

    const { Component } = ctx
    let pageProps = {}
    if (Component.getInitialProps) {
     pageProps = await Component.getInitialProps(ctx)
    }

    return {
      pageProps,
    }
  }

  render() {
    const { Component, pageProps, reduxStore } = this.props
    return (
      <Container>
        <Layout>
          <Provider store={reduxStore}>
            <Component {...pageProps} />
          </Provider>
        </Layout>
      </Container>
    )
  }
}

export default withRedux(MyApp)

在我的with-redux-app.jsx中

import React from 'react'
import initializeStore from '../redux/store'

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

function getOrCreateStore(initialState) {
  if (isServer) {
    return initializeStore(initialState)
  }

  if (!window[__NEXT_REDUX_STORE__]) {
    window[__NEXT_REDUX_STORE__] = initializeStore(initialState)
  }
  return window[__NEXT_REDUX_STORE__]
}

export default Comp => {
  class withReduxApp extends React.Component {
    constructor(props) {
      super(props)
      this.reduxStore = getOrCreateStore(props.initialReduxState)
    }

    render() {
      const { Component, pageProps, ...rest } = this.props
      return (
        <Comp
          {...rest}
          Component={Component}
          pageProps={pageProps}
          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
}

我收到服务器错误: 在此处输入图片说明

我能怎么做 ?

约翰

您应该将所有组件包装在redux提供程序中。

<Provider store={reduxStore}>
  <Layout>
    <Container>
      <Component {...pageProps} />
    </Container>
  </Layout>
</Provider>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章