不变违规:根路由必须在 react-router 2 动态路由中呈现单个元素错误 [英] Invariant Violation: The root route must render a single element error in react-router 2 dynamic routing

查看:51
本文介绍了不变违规:根路由必须在 react-router 2 动态路由中呈现单个元素错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的 Hello World 应用程序,其中一条路由没有子路由或索引路由.对于路由我使用 plain路线 而不是 jsx sysntax.我再次使用 react-router 的 动态路由使用 webpack 加载 Hello 组件.我的 app.jsx 文件具有以下代码.

I have simple Hello World App with one route no child route or index route. For routing i using plain routes instead of jsx sysntax. Again i am using react-router's dynamic routing to load Hello component with webpack. My app.jsx file has the following code.

import React from "react";
import ReactDOM from "react-dom";
import {Router, browserHistory} from "react-router";
import Hello from "./components/Hello";



const routes = [{
    path:"/",
    getComponents(location, callback) {
        require.ensure([], function (require) {
            callback(null, require('./components/Hello'))
        })
    }
}];


ReactDOM.render(
    <Router history={browserHistory}  routes={routes}/>,
    document.getElementById("container")
); 

Hello.jsx 组件有如下代码

import React from "react";
export default class Hello extends React.Component {

    render() {

        return (
            <h2>Hello World</h2>
        )
    }
}

推荐答案

出现这个错误是因为webpack不支持es6模块

This error happens because webpack doesn't support es6 modules

如果您使用 babel 来转译 es6 代码,请使用默认关键字,如

if you are using babel to transpile es6 code then use the default keyword like

require('./components/Hello').default

所以路线将是

const routes = [{
    path:"/",
    getComponents(location, callback) {
        require.ensure([], function (require) {
            callback(null, require('./components/Hello').default)
        })
    }
}];

这篇关于不变违规:根路由必须在 react-router 2 动态路由中呈现单个元素错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆