获取异步组件时,React路由器抛出并出错

时间:2016-03-11 17:01:26

标签: react-router redux

我正在使用react,redux和react路由器来构建其他人以及示例app。

我试图异步加载应用程序的不同部分。我已经将我的应用程序划分为鸭子了,我跟随此示例https://github.com/insin/react-examples/tree/master/code-splitting-redux-reducers

但是我收到了这个错误:

Uncaught Invariant Violation: The root route must render a single element

尝试使用反应路由器的getComponent方法获取异步组件时。 我正在使用: react-router 2.0.1

我的路线:

export default function configureRoutes(reducerRegistry) {
  return(
    <Route>
      <Route component={Landing}>
        <Route path='/login' component={Login}/>
        <Route path='/register' component={Register}/>
      </Route>
            <Route path="admin" getComponent={(location, cb) => {
                require.ensure([], require => {
                    cb(null, require('./containers/admin'))
                })
            }}/>
      <Route component={App}>
        <Route  path='/' component={Home} />
      </Route>
    </Route>
)}

我的组件

class Admin extends Component {
  componentDidMount() {
    this.props.load()  
  }
  render() {
    const { message, isFetching } = this.props
    return (
      <div>
        <p>{message}</p> 
        <p>This module was loaded via chunk </p>
        {loading && <p>Doing some fake loading ...</p>}
      </div>
    )  
  }  
}

Admin.propTypes = {
  message: PropTypes.string.isRequired,
  isFetching: PropTypes.bool.isRequired,
  load: PropTypes.string.isRequired
}

const mapStateToProps = state => state.admin

function mapDispatchToProps(dispatch) {
  return bindActionCreators({ load }, dispatch)
}

export default connect(mapStateToProps, mapDispatchToProps)(Admin)

有没有人有同样的错误?有任何想法吗?有人有类似的工作吗?

感谢社区!

更新:为清晰起见添加了index.js

import configureRoutes from './routes'
import configureStore from './store/configureStore'
import coreReducers from './modules/core'
import ReducerRegistry from './reducer-registry'

var reducerRegistry = new ReducerRegistry(coreReducers)

// Configure hot module replacement for core reducers
if (process.env.NODE_ENV !== 'production') {
  if (module.hot) {
    module.hot.accept('./modules/core', () => {
      var nextCoreReducers = require('./modules/core')
      reducerRegistry.register(nextCoreReducers)
    })
  }
}

const routes = configureRoutes(reducerRegistry)
const store = configureStore(reducerRegistry)

render(
  <I18nextProvider i18n={i18n}>
    <Provider store={store}>
      <Router history={browserHistory} routes={routes} />
    </Provider>
  </I18nextProvider>,
  document.getElementById('root')
)

1 个答案:

答案 0 :(得分:2)

我认为您的根<Route>缺少component字段。

您需要为每个父路由指定componentgetComponent,因为这将是当前子路由的组件传递给this.props.children的组件。

而不是

export default function configureRoutes(reducerRegistry) {
  return (
    <Route>

你想要像

这样的东西
export default function configureRoutes(reducerRegistry) {
  return (
    <Route component={App}>

在这种情况下,您可能不需要下面的其他App路线。