Reactjs 如何通过React router 5以编程方式提升路由层次结构的一级?
在我的项目中,我有一个功能需求,它应该有一个后退按钮,可以将用户导航到路由层次结构的上一层 考虑到我有以下路线:Reactjs 如何通过React router 5以编程方式提升路由层次结构的一级?,reactjs,react-router-v5,Reactjs,React Router V5,在我的项目中,我有一个功能需求,它应该有一个后退按钮,可以将用户导航到路由层次结构的上一层 考虑到我有以下路线: // Home Component <div> <Route path="/courses" component={CourseComponent} /> <Route path="/settings" component={SettingsComponent} /> </div> //主组件 嵌套路由: // Co
// Home Component
<div>
<Route path="/courses" component={CourseComponent} />
<Route path="/settings" component={SettingsComponent} />
</div>
//主组件
嵌套路由:
// Course Component
<Switch>
<Route path={`${match.path}/:courseId/details`} component={CourseDetailComponent} />
<Route path={`${match.path}/classes`} component={ClassComponent} />
<Route
exact
path={match.path}
render={() => <h3>Courses...</h3>}
/>
</Switch>
//课程组件
课程…}
/>
现在我想使用后退按钮将用户从CoursedDetailComponent
导航到CourseComponent
注意:我不能使用history
,因为考虑到以下情况,这将使用浏览器历史记录:如果用户使用URL直接登录页面
您必须在应用程序中使用一个组件,它知道所有更改。因此,您可以拥有一个父应用程序组件,它将收到所有更改的通知
<Route component={App}>
{/* ... other routes */
</Route>
var App = React.createClass({
getInitialState () {
return { showBackButton: false }
},
componentWillReceiveProps(nextProps) {
var routeChanged = nextProps.location !== this.props.location
this.setState({ showBackButton: routeChanged })
}
})
{/*…其他路线*/
var App=React.createClass({
getInitialState(){
返回{showBackButton:false}
},
组件将接收道具(下一步){
var routeChanged=nextrops.location!==this.props.location
this.setState({showBackButton:routeChanged})
}
})
此处参考:您必须在应用程序中使用一个组件,该组件知道所有更改。因此,您可以拥有一个父应用程序组件,该组件将收到所有更改的通知
<Route component={App}>
{/* ... other routes */
</Route>
var App = React.createClass({
getInitialState () {
return { showBackButton: false }
},
componentWillReceiveProps(nextProps) {
var routeChanged = nextProps.location !== this.props.location
this.setState({ showBackButton: routeChanged })
}
})
{/*…其他路线*/
var App=React.createClass({
getInitialState(){
返回{showBackButton:false}
},
组件将接收道具(下一步){
var routeChanged=nextrops.location!==this.props.location
this.setState({showBackButton:routeChanged})
}
})
此处引用:我怀疑您需要手动执行此操作。考虑到
${match.path},可能需要获取当前url并删除最后一个路径/:courseId/details
url,删除最后一个路径不会解决问题!我想知道react-router-v5
是否提供类似的东西,否则我必须自己做!我怀疑您需要手动完成。考虑到${match.path},可能需要获取当前url并删除最后一个路径/:courseId/details
url,删除最后一条路径不会解决问题!我想知道react-router-v5
是否提供类似的东西,否则我必须自己做!这只会告诉应用程序用户是否直接登录到该页面,但这不是我要找的!我想转到tha的父路径无论窗口历史记录是什么,t子路由。如果它在您的根目录中,组件将始终被激活。您可以从那里跟踪它。您只需要将所有路由放在一个组件中,就像这样。您是否建议创建我的应用程序中使用的所有路由的地图?这只会告诉应用程序,如果用户直接登录到无论是否在第页,但这不是我要找的!我想转到该子路由的父路由,无论窗口历史是什么。如果它在您的根目录中,组件将始终被激活。您可以从那里跟踪它。您只需要将所有路由放在这样的组件中。您建议创建所有路由的映射吗我的申请中使用了什么?