带有 React Router 的嵌套组件

Nested components with React Router

我正在学习在线 React 教程。在我下载 React Router(和 react-router-dom)时获得 React Router 4 时使用的教程 React Router 3。教程中的代码如下所示。

import React from "react";
import {render} from "react-dom";
import {Router, Route, browserHistory} from 'react-router'

import {Root} from "./components/Root";
import {Home} from "./components/Home";
import {User} from "./components/User";

class App extends React.Component {
    render() {
        return (
            <Router history={browserHistory}>
                <Route path={"/"} component={Root}>
                    <Route path={"user"} component={User}/>
                    <Route path={"home"} component={Home}/>
                </Route>
            </Router>
        );
    }
}

render(<App />, window.document.getElementById('app'));  

我正在尝试重写代码以像这样使用 React Router 4:

import React from "react";
import {render} from "react-dom";
import {Switch, BrowserRouter, Route} from 'react-router-dom'

import {Root} from "./components/Root";
import {Home} from "./components/Home";
import {User} from "./components/User";

class App extends React.Component {
    render() {
        return (
            <BrowserRouter>
                <Switch>
                    <Route path="/" component={Root}>
                        <Route path="/user" component={User}/>
                        <Route path="/home" component={Home}/>
                    </Route>
                </Switch>
            </BrowserRouter>
        );
    }
}

render(<App />, window.document.getElementById('app'));

这给了我一个错误:

Warning: You should not use <Route component> and <Route children> in the same route; <Route children> will be ignored

我试过用 <Switch><Root> 包装子组件,但没有成功。子组件应该如何包装?

在 React Router 4 中,您不再嵌套路由。在你的情况下,你可以做的是将你的路由放在你的子组件中,如下所示:

class App extends React.Component {
    render() {
        return (
            <BrowserRouter>
                <Route path="/" component={Root} />
            </BrowserRouter>
        );
    }
}

class Root extends React.Component {
    render() {
        return (
            <div>
                <Route path="/user" component={User}/>
                <Route path="/home" component={Home}/>
            </div>
        );
    }
}

此外,我认为您不需要在此处使用 Switch,因为它只会匹配第一个子路由,而您的情况似乎不需要它。