使用React Router的嵌套组件

时间:2017-06-21 11:19:38

标签: reactjs react-router react-router-v4

我正在关注在线反应教程。在我下载React Router 4(和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>包装子组件,但它不起作用。如何包装子组件?

1 个答案:

答案 0 :(得分:2)

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

listView.setAdapter(nameOfYourAdapter)

另外,我认为你不需要在这里使用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> ); } } ,因为它只会匹配一个第一个子路由,而在你的情况下似乎不需要它。