反应路由器路由中的尾部正斜杠

Trailing forward slash in react-router routes

我正在使用 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

你应该使用像

这样的路由设置
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 是绝对路线,因为它以 / 开头。我认为更好的方法是删除它并使用路由 as

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

您的第一次设置失败的原因是 React Router <Route> path嵌套。

您的第二个设置很接近,但您不应在 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'));