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

Ken*_*den 7 javascript jsx reactjs react-router

我正在使用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'));
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,我Route的应用程序基础有一条路径'shop'.就用户而言,这应该导致2条不同的路线,http://example.com/shop并且http://example.com/shop/product.然而,这种情况并非如此.

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

Warning: [react-router] Location "/shop/product" did not match any routes
Run Code Online (Sandbox Code Playgroud)

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

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'));
Run Code Online (Sandbox Code Playgroud)

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

是可以渲染http://example.com/shop,http://example.com/shop/,http://example.com/shop/product在同一应用程序内?

Pau*_*l S 7

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

你的第二个设置很接近,但你不应该在shop/. React Router 会为您将路径连接在一起,您无需担心在 joinshopproduct. (例如,看看这个使用相对路径的配置

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'));
Run Code Online (Sandbox Code Playgroud)