React Router没有加载页面

时间:2017-06-20 10:49:40

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

我正在关注在线反应教程。在我下载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>
                <Route path={"user"} component={User}/>
                <Route path={"home"} component={Home}/>
            </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={"user"} component={User}/>
                    <Route path={"home"} component={Home}/>
                </Switch>
            </BrowserRouter>
        );
    }
}

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

User.js的代码如下所示:

import React from "react";

export class User extends React.Component {
    render() {
        return (
            <div>
                <h3>The User Page</h3>
                <p>User ID: </p>
            </div>
        );
    }
}

当我尝试localhost:8080/user时,它什么都不返回。

我只得到

<div id="app">
    <!-- react-empty: 1 -->
</div>

我需要在代码中更改什么?

1 个答案:

答案 0 :(得分:1)

尝试

<Route path="/user" component={User}/>