我使用react-router-dom
为我的反应项目,我有这个基本的路由结构
<Router>
<div className="app-container">
<Navbar />
<Suspense fallback={<ReactLazyLoadingScreen />}>
<Switch>
{getRoutes(isAuthenticated, privateRoutes)}
<Route exact path="/:courseSlug" component={CourseDetailsContainer} />
<Redirect to="/404" />
</Switch>
</Suspense>
</div>
</Router>
这里,当动态路径/:courseSlug
的路由被渲染时,我想知道在Navbar
组件中。
在Navbar
组件中,我使用WithRouter
HOC导出,如下所示
export default withRouter(
connect(mapStateToProps, mapDispatchToProps)(NavbarComponent)
)
当我尝试访问location
或history
时,没有属性可以用来表示CourseDetailsContainer
被渲染。
const { history, location } = this.props;
console.log({ props: this.props });
console.log({ history, location });
如何解决这个问题?
您应该能够使用props.computedMatch
:
let courseSlug = props?.computedMatch?.params?.courseSlug
我不是100%确定你可以通过<Navbar>
组件访问它,所以你可能要检查它在<Route>
组件内,然后传递布尔值到你的<Router>
,或者使用redux配置跨组件通信的数据。