React Router 导航不会改变 page/component

React Router navigation doesn't change the page/component

我正在使用最新版本的 react-router (^3.0.0)。

我正在尝试创建一个简单的导航,但我无法更改根据 url 路径显示的组件。

这是我的简单路由代码:

ReactDom.render(
    <Router history={browserHistory}>
        {routes}        
    </Router>,
    document.getElementById('app')
);

这是我的路线变量:

var routes = (
    <Route path="/" component={App}>
        <IndexRoute component={Home} />
        <Route path="authors" component={AuthorPage} />
    </Route>

);

当我导航到 http://localhost:9005/#/authors 时,我仍然显示 App 组件。我知道我的路由确实识别了作者路径,因为如果我输入了错误的路径(比如 authors1),那么我会收到一条错误消息,指出该路径不存在。我尝试同时使用 browserHistory 和 hashHistory。

假设我的路由确实识别作者路径,为什么它不根据作者组件更改页面内容?

谢谢

使用 react-router 的 Match 和 Miss 方法。 Match 允许您设置要路由到的确切组件的规则,如果路由 404:

,则 Miss 设置目的地
import React from 'react';
import {render} from 'react-dom';
import {BrowserRouter, Match, Miss} from 'react-router';
import NotFound from './components/NotFound';

const Root = () => {
    return(
        <BrowserRouter>
            <div>
                <Match exactly pattern="/" component={App} />
                <Match exactly pattern="/authors" component={AuthorPage}/>
                <Miss component={NotFound} />
            </div>
        </BrowserRouter>
    )
}

render(<Root/>, document.querySelector('#main'));

可能唯一的问题是您忘记了作者前面的斜线(“/作者”)

ReactDom.render(
    <Router history={browserHistory}>
       <Route path="/" component={App}>
           <IndexRoute component={Home} />
           <Route path="/authors" component={AuthorPage} />
      </Route>    
    </Router>,
    document.getElementById('app')
);

希望对您有所帮助。