首页 > 解决方案 > 如何使用 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>

现在我想将用户导航CourseDetailComponentCourseComponent使用该后退按钮。

注意:我不能使用history,因为考虑到这种情况,这将使用浏览器历史记录:如果用户使用 URL 直接登陆页面。

标签: reactjsreact-router-v5

解决方案


你必须在你的应用程序中使用一个组件,它知道所有的变化。因此,您可以拥有一个父 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


推荐阅读