在反应路由器路由中追踪正斜杠

时间:2016-12-19 05:37:51

标签: javascript reactjs react-router jsx

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

2 个答案:

答案 0 :(得分:2)

第一次设置失败的原因是因为以斜杠开头的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'));

答案 1 :(得分:0)

您应该使用

之类的路线设置
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路线绝对是您的网址,因为它以/开头。我认为更好的方法是删除它并使用路径

<Route path='product' component={ProductView} />
相关问题