1

我正在尝试捆绑路由,然后在它们在 reacttraining(https://reacttraining.com/react-router/web/guides/code-splitting)加载示例时渲染它们,但是我在使用 Bundle 的渲染方法时遇到错误零件。我还尝试按原样制作一个组件而不进行捆绑,以防它可能尚未加载但没有工作。任何帮助表示赞赏。

React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: null. Check the render method of 'Bundle'.

Uncaught (in promise) TypeError: Cannot read property '_currentElement' of null

我的捆绑组件:

import React, { Component } from 'react'

export default class Bundle extends Component {
  constructor(props) {
    super(props)
    this.state = {
      // short for "module" but that's a keyword in js, so "mod"
      mod: null
    }
  }

  componentWillMount() {
    this.load(this.props)
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.load !== this.props.load) {
      this.load(nextProps)
    }
  }

  load(props) {
    this.setState({
      mod: null
    })
    props.load((mod) => {
      this.setState({
        // handle both es imports and cjs
        mod: mod.default ? mod.default : mod
      })
    })
  }

  render() {
    console.log(`console`)
    console.log(this.props.children(this.state.mod))
    return this.props.children(this.state.mod)
  }
} 

我的带有路由的根组件:

import React, { Component } from 'react'
import {
  BrowserRouter as Router,
  Route,
  Switch
} from 'react-router-dom'
import loadMainPage from 'bundle-loader?lazy!./../components/MainPage'
import loadLocation from 'bundle-loader?lazy!./../components/Location'
import Bundle from '../components/Bundle'
import 'bootstrap/dist/css/bootstrap.css'
import 'babel-polyfill'

export const Location = () => (
  <Bundle load={loadLocation}>
    {(Location) => <Location/>}
  </Bundle>
)

export const MainPage = () => (
  <Bundle load={loadMainPage}>
    {(MainPage) => <MainPage/>}
  </Bundle>
)

class Root extends Component {
  constructor(props) {
    super(props)
  }
  componentDidMount() {
    loadMainPage(() => {})
    loadLocation(() => {})
  }
  render() {
    return (
      <Router>
        <Switch>
          <Route exact path="/" component={MainPage} />
          <Route path="/bar" component={Location} />
          <Route path="/barbershop" component={Location} />
        </Switch>
      </Router>
    )
  }
}

export default Root 

我的 app.js:

import React from 'react'
import ReactDOM from 'react-dom'
import Root from './containers/Root'
import 'bootstrap/dist/css/bootstrap.css'
import { Provider } from 'react-redux'
import { configureStore, sagaMiddleware } from './configureStore'
import rootSaga from './sagas/index'

const store = configureStore()

sagaMiddleware.run(rootSaga)

ReactDOM.render(
  <Provider store={store}>
    <Root />
  </Provider>,
  document.getElementById('root')
) 
4

1 回答 1

1

糟糕,在加载包时忘记添加处理。像这样:

const Location = () => (
  <Bundle load={loadLocation}>
    {
      (Location) => Location
      ? <Location/>
      : <Loading text='Loading...' />
    }
  </Bundle>
) 
于 2017-06-02T15:02:26.730 回答