reactjs - 如何使用 React 路由器 5 以编程方式将路由层次结构提升一级?
问题描述
我的项目中有一个功能要求,它应该有一个后退按钮,可以将用户导航到路由层次结构的上一级。
考虑我有以下路线:
// 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>
现在我想将用户导航CourseDetailComponent
到CourseComponent
使用该后退按钮。
注意:我不能使用
history
,因为考虑到这种情况,这将使用浏览器历史记录:如果用户使用 URL 直接登陆页面。
解决方案
你必须在你的应用程序中使用一个组件,它知道所有的变化。因此,您可以拥有一个父 App 组件,它将收到所有更改的通知
<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 })
}
})
参考这里:https ://github.com/ReactTraining/react-router/issues/1066#issuecomment-139233328
推荐阅读
- laravel - laravel 控制台中的 SQS 队列
- windows - 有没有办法使用 python 获取活动 Windows 资源管理器的 URL
- permissions - 在 actions.intent.PERMISSION 中没有听到 conv.ask('...'') 的讲话
- c# - Implementing DataTables using EF. No results showing, no errors
- php - PHP 未捕获错误:在 null 上调用成员函数 userRole()
- python - 创建新记录时如何根据其他字段更改字段只读值?
- r - 如何在闪亮的网络应用程序中从不同文件夹上传多个文件?
- sql - T-SQL解析XML给出空白值
- webpack - VuePress:如何导入 css 框架(basscss)
- html - django 中 bootstrap 3 的 CSS 没有按预期工作