在React Router/browserHistory中获取当前路由的路径名
问题描述:
在使用React Router获取当前URL的路径名的最有效方式是(使用browserHistory
)的各种源之间似乎存在一些不一致。下面是我的供应商和路线的一个片段:在React Router/browserHistory中获取当前路由的路径名
ReactDOM.render(
<Provider store={Store}>
<Router history={browserHistory}>
<Route path="/tools/customer-lookup" component={CustomerLookupApp} />
<Route path="/tools/customer-lookup/profile/:id" component={CustomerLookupProfileWrapper} />
<Route path="/tools/customer-lookup/profile/:id/store/:storeid" component={CustomerLookupStoreProfileWrapper} />
<Route path="/tools/customer-lookup/profile/:id/store/:storeid/transaction/:transid" component={CustomerLookupStoreItemsWrapper} />
</Router>
</Provider>,
document.getElementById('customer-lookup-main'));
});
登录尝试各种成分this.props.location.pathname
但总是出现不确定的。与this.context
一样的东西。
任何意见表示赞赏,谢谢。
答
该属性this.props.location.pathname
将不会在“各种”组件中可用,它只会在您的路由处理组件中可用。即CustomerLookupApp
,CustomerLookupProfileWrapper
,CustomerLookupStoreProfileWrapper
,CustomerLookupStoreItemsWrapper
。
如果你需要进一步在树下的路径名,那么你可以把它作为道具传递下去。
+0
我仍然可以通过它吗? '
你的代码似乎是正确的,除了你的路线路线有点多余。你可以使用子路径来减少'path'的长度。您可以发布完整的代码,以便调试.red –
@JasonXu除了我试图**避免**在旅行到儿童路线时将一个组件嵌套在另一个组件中。相反,路线(虽然我同意他们看起来非常冗余)链接到一个完全不同的单页面应用程序的视图,并不一定重用任何父组件。如果有更好的方法来完成**并且仍然嵌套路线,我很有兴趣听到它。 – Jose