使用React Loadable

时间:2018-06-25 14:33:03

标签: reactjs webpack code-splitting dynamic-import react-loadable

使用React Loadable时遇到问题,而使用Webpack 3.11进行基于路由的代码拆分。

当我尝试在服务器上呈现我的应用程序时,我的异步模块会立即解析,而无需等待承诺。因此,SSR输出变为<div id="root"></div>

App.js:

const App = () => (
  <Switch>
    {routes.map((route, index) => (
      <Route key={index} path={route.path} render={routeProps => {
        const RouteComponent = route.component
        return <RouteComponent {...routeProps} />
      }} />
    ))}
  </Switch>
)

我已经使用React Loadable定义了异步路由组件,如下所示:

Routes.js

function Loading ({ error }) {
  if (error) {
    return 'Oh nooess!'
  } else {
    return <h3>Loading...</h3>
  }
}

const Article = Loadable({
  loader: () => import(/* webpackChunkName: "Article" */ '../components/contentTypes/Article'),
  loading: Loading
})

const Page = Loadable({
  loader: () => import(/* webpackChunkName: "Page" */ '../components/contentTypes/Page'),
  loading: Loading,
  render (loaded, props) {
    let Component = WithSettings(loaded.default)
    return <Component {...props}/>
  }
})

export default [
  {
    path: `/:projectSlug/:env${getEnvironments()}/article/:articleSlug`,
    component: Article,
    exact: true
  },
  {
    path: `/:projectSlug/:env${getEnvironments()}/:menuSlug?/:pageSlug?`,
    component: Page
  }
]

WithSettings.js

export default (WrappedComponent: any) => {
  class WithSettings extends React.Component<WithSettingsProps, WithSettingsState> {
    static displayName = `WithSettings(${WrappedComponent.displayName || WrappedComponent.name || 'Component'})`

    state = {
      renderWidth: 1200
    }

    componentDidMount () {
      this.loadSettings({ match: { params: { projectSlug: '', env: '' } } })
      window.addEventListener('resize', this.onResize)
      this.onResize()
    }

    componentWillUnmount () {
      if (isClient) {
        window.removeEventListener('resize', this.onResize)
      }
    }

    componentDidUpdate (oldProps) {
      this.loadSettings(oldProps)
    }

    onResize = () => {
      this.setState({ renderWidth: this.getLayoutWidth() })
    }

    getLayoutWidth () {
      return (document.body && document.body.offsetWidth) || 0
    }

    loadSettings (oldProps) {
      const { settings, request, getNewSettings } = this.props
      const { projectSlug: oldProjectSlug, env: oldEnv } = oldProps.match.params
      const { projectSlug: newProjectSlug, env: newEnv } = this.props.match.params

      if (
        (
          oldProjectSlug !== newProjectSlug ||
          oldEnv !== newEnv
        ) ||
        (
          settings === undefined ||
          (request.networkStatus === 'ready')
        )
      ) {
        getNewSettings()
      }
    }

    render () {
      const { settings, request, history, location, match } = this.props
      const { renderWidth } = this.state

      if (!settings || !request || request.networkStatus === 'loading') {
        return <div />
      }

      if (request.networkStatus === 'failed') {
        return <ErrorBlock {...getErrorMessages(match.params, 'settings')[4044]} fullscreen match={match} />
      }

      return (
        <WrappedComponent
          settings={settings}
          settingsRequest={request}
          history={history}
          location={location}
          match={match}
          renderWidth={renderWidth}
        />
      )
    }
  }

  hoistNonReactStatic(WithSettings, WrappedComponent)

  return connect(mapStateToProps, mapDispatchToProps)(WithSettings)
}

我设法将其范围缩小到用于包裹路线组件的WithSettings HOC。如果我不使用WithSettings HOC(与Article路线一样)然后我的SSR输出等待异步导入完成,并且服务器生成的html包含与路由相关的标记(好!)。如果我确实使用HOC(与Page路由一样),则该模块会立即解析,并且我的SSR输出变成<div id="root"></div,因为它不再等待动态导入完成才渲染。问题是:我需要在所有路由中使用WithSettings HOC,因为它会从服务器上获取我需要渲染应用程序的数据。

谁能告诉我如何使用HOC 将React Loadable的异步组件用于路由组件,以便它可以在服务器上工作?

1 个答案:

答案 0 :(得分:0)

设法弄清楚了。

这是由于我的HOC。在render方法中,当<div />settings的位置未定义或requestrequest.networkStatus时,它将返回loading。事实证明,这跳了服务器端渲染。删除该块足以使其正常工作。