【问题标题】:Trailing forward slash in react-router routesreact-router 路由中的尾部正斜杠
【发布时间】:2017-05-04 03:14:51
【问题描述】:

我正在使用 react-router v3.0.0 和 react v15.1.0。我有以下路线设置:

ReactDom.render(<Provider store={store}>
    <Router history={BrowserHistory}>
        <Route path='shop' component={App}>
            <IndexRoute component={Shop} />
            <Route path='/product' component={ProductView} />
        </Route>
    </Router>
</Provider>, document.getElementById('app'));

如您所见,我的应用程序基础Route 的路径为'shop'。就用户而言,这应该导致 2 个单独的路由,http://example.com/shophttp://example.com/shop/product。然而,这种情况并非如此。

当我部署上述代码时,http://example.com/shop 正确呈现,但 http://example.com/shop/product 没有呈现任何内容。事实上,我得到一个控制台错误:

Warning: [react-router] Location "/shop/product" did not match any routes

所以,我稍微改变了我的设置:

ReactDom.render(<Provider store={store}>
    <Router history={BrowserHistory}>
        <Route path='shop/' component={App}>
            <IndexRoute component={Shop} />
            <Route path='product' component={ProductView} />
        </Route>
    </Router>
</Provider>, document.getElementById('app'));

这将允许我渲染http://example.com/shop/(注意尾部正斜杠)、http://example.com/shop/product但不是http://example.com/shop

是否可以在同一个应用中呈现http://example.com/shophttp://example.com/shop/http://example.com/shop/product

【问题讨论】:

  • /shop//shop 意思相同,因此无法区分。但/shop/product与那些不同,可以区分。

标签: javascript reactjs react-router jsx


【解决方案1】:

你应该像这样使用路由设置

ReactDom.render(<Provider store={store}>
    <Router history={BrowserHistory}>
        <Route path='shop' component={App}>
            <IndexRoute component={Shop} />
            <Route path='/shop/product' component={ProductView} />
        </Route>
    </Router>
</Provider>, document.getElementById('app'));

您的路由不起作用,因为您的 product 路由与您的 url 是绝对的,因为它以 / 开头。我认为更好的方法是删除它并将路线用作

<Route path='product' component={ProductView} />

【讨论】:

    【解决方案2】:

    您的第一次设置失败的原因是因为以斜杠开头的 React Router &lt;Route&gt; paths 被认为是绝对根 (/),即使它们是嵌套的。

    您的第二个设置已接近,但您不应在shop/ 中包含尾部斜杠。 React Router 将为您将路径连接在一起,您无需担心包含斜线来连接 shopproduct。 (例如,查看使用相对路径的this configuration

    ReactDom.render(<Provider store={store}>
      <Router history={BrowserHistory}>
        <Route path='shop' component={App}>
            <IndexRoute component={Shop} />
            <Route path='product' component={ProductView} />
        </Route>
      </Router>
    </Provider>, document.getElementById('app'));
    

    【讨论】:

    • 啊,这行得通。非常感谢!如果您要编辑答案以包含工作代码,那么我很乐意接受答案。
    • 完成。 React Router 与相对路径有点混淆,因为 &lt;Route&gt;s 可以使用它们,但 &lt;Link&gt;s 不能,但它就是这样:/
    猜你喜欢
    • 2018-05-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-09
    • 2020-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多