反应路由器路由中的尾随正斜杠 [英] Trailing forward slash in react-router routes
问题描述
我正在将react-router v3.0.0与react v15.1.0一起使用.我有以下路线设置:
I am using react-router v3.0.0 with react v15.1.0. I have the following route setup:
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'
.就用户而言,这应该会导致两条单独的路线http://example.com/shop
和http://example.com/shop/product
.然而,这种情况并非如此.
As you can see, my base Route
for the application has a path of 'shop'
. As far as the user is concerned, this should result in 2 separate routes, http://example.com/shop
and http://example.com/shop/product
. However, this is not the case.
当我部署上述代码时,http://example.com/shop
可以正确呈现,但是http://example.com/shop/product
则不呈现任何内容.实际上,我收到一个控制台错误:
When I deploy the aforementioned code, http://example.com/shop
renders correctly, but http://example.com/shop/product
renders nothing. In fact, I get a console error:
Warning: [react-router] Location "/shop/product" did not match any routes
因此,我对设置进行了一些更改:
So, I altered my setup a bit:
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
.
This will allow me to render http://example.com/shop/
(notice the trailing forward slash), http://example.com/shop/product
, but NOT http://example.com/shop
.
是否可以在同一应用中渲染http://example.com/shop
,http://example.com/shop/
,http://example.com/shop/product
?
Is is possible to render http://example.com/shop
, http://example.com/shop/
, http://example.com/shop/product
within the same app?
推荐答案
首次设置失败的原因是因为以斜杠开头的React Router <Route>
path
被认为是绝对的根目录(/
),即使它们是嵌套的.
The reason that your first setup failed is because React Router <Route>
path
s that begin with a slash are considered absolute to the root (/
), even when they are nested.
您的第二个设置已结束,但您不应在shop/
中包括斜杠. React Router将为您将路径连接在一起,您无需担心要加入shop
和product
的斜线. (例如,查看此配置(使用相对路径)
Your second setup is close, but you should not include the trailing slash in shop/
. React Router will join the paths together for you, you do not need to worry about including a slash to join shop
and product
. (For example, look at this configuration which uses relative paths)
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'));
这篇关于反应路由器路由中的尾随正斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!