【问题标题】:React Router navigation doesn't change the page/componentReact Router 导航不会改变页面/组件
【发布时间】:2017-04-15 00:42:44
【问题描述】:

我正在使用最新版本的 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。

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

谢谢

【问题讨论】:

    标签: reactjs react-router browserify


    【解决方案1】:

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

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

    希望对您有所帮助。

    【讨论】:

    • 好的,非常感谢。
    【解决方案2】:

    使用 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'));
    

    【讨论】:

    • &lt;Match&gt;&lt;Miss&gt; 是 v4,但 OP 使用的是 v3
    猜你喜欢
    • 2020-07-09
    • 2022-12-17
    • 2016-10-11
    • 1970-01-01
    • 2020-09-29
    • 1970-01-01
    • 2016-09-28
    • 2019-11-17
    • 2020-01-22
    相关资源
    最近更新 更多