如何在父路由组件中获取参数 [英] How to get params in parent route component

查看:41
本文介绍了如何在父路由组件中获取参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 React、React-Router (v5) 和 Redux 构建一个应用程序,想知道如何在父路由中访问当前 URL 的参数.

I'm building an app with React, React-Router (v5) and Redux and wonder how to access the params of the current URL in a parent route.

这是我的条目,router.js:

<Wrapper>
  <Route exact path="/login" render={(props) => (
    <LoginPage {...props} entryPath={this.entryPath} />
  )} />

  <Route exact path="/" component={UserIsAuthenticated(HomePage)} />
  <Route exact path="/about" component={UserIsAuthenticated(AboutPage)} />
  <Route path="/projects" component={UserIsAuthenticated(ProjectsPage)} />
</Wrapper>

这就是我的 ProjectsPage 组件:

class ProjectsPage extends PureComponent {
  componentDidMount() {
    this.props.fetchProjectsRequest()
  }

  render() {
    console.log(this.props.active)

    if (this.props.loading) {
      return <Loading />
    } else {
      return (
        <Wrapper>
          <Sidebar>
            <ProjectList projects={this.props.projects} />
          </Sidebar>
          <Content>
            <Route exact path="/projects" component={ProjectsDashboard} />

            <Switch>
              <Route exact path="/projects/new" component={ProjectNew} />
              <Route exact path="/projects/:id/edit" component={ProjectEdit} />
              <Route exact path="/projects/:id" component={ProjectPage} />
            </Switch>
          </Content>
        </Wrapper>
      )
    }
  }
}

const enhance = connect(
  (state, props) => ({
    active: props.match,
    loading: projectSelectors.loading(state),
    projects: projectSelectors.projects(state)
  }),
  {
    fetchProjectsRequest
  }
)

export default withRouter(enhance(ProjectsPage))

问题是,我的 render 方法中的 console.log 输出是 {"path":"/projects","url":"/projects","isExact":false,"params":{}} 虽然 URL 是 http://localhost:3000/projects/14.

The problem is, that the console.log output in my render method is {"path":"/projects","url":"/projects","isExact":false,"params":{}} although the URL is http://localhost:3000/projects/14.

我想向我的 ProjectList 添加一个 ID 道具以突出显示当前选定的项目.

I want to add an ID prop to my ProjectList to highlight the currently selected project.

我可以将项目的 ID 保存在我的 ProjectPage 组件内的商店中,但我认为这会有点令人困惑,尤其是因为 URL 实际上包含信息——所以我为什么要写店里有东西吗?

I could save the ID of the project in a store inside my ProjectPage component, but I think this would be a bit confusing, especially because the URL has the information actually – so why should I write something in the store?

另一种(坏的?)方法是解析位置对象并自己获取 ID,但我认为有一个 react-router/react-router-redux在这一点上我忽略了获取参数的方法.

Another (bad?) approach would be to parse the location object the get the ID by myself, but I think there is a react-router/react-router-redux way to get the params at this point that I've overlooked.

推荐答案

@Kyle 从技术角度很好地解释了问题.我只会专注于解决那个问题.

@Kyle explained issue very well from technical perspective. I will just focus on solution to that problem.

您可以使用 matchPath 获取所选项目的 id.

You can use matchPath to get id of selected project.

ma​​tchPath - https://reacttraining.com/react-router/web/api/matchPath

这让您可以使用相同的匹配代码,除了在正常渲染周期之外,比如收集数据在服务器上呈现之前的依赖项.

This lets you use the same matching code that uses except outside of the normal render cycle, like gathering up data dependencies before rendering on the server.

在这种情况下使用非常简单.

Usage in this case is very straight forward.

// history is one of the props passed by react-router to component
// @link https://reacttraining.com/react-router/web/api/history

const match = matchPath(history.location.pathname, {
  // You can share this string as a constant if you want
  path: "/articles/:id"
});

let articleId;

// match can be null
if (match && match.params.id) {
  articleId = match.params.id;
}

2 在渲染中使用 articleId

{articleId && (
  <h1>You selected article with id: {articleId}</h1>
)}

我构建了一个简单的演示,您可以使用它在您的项目中实现相同的功能.

I build a simple demo which you can use to implement the same functionality in your project.

演示: https://codesandbox.io/s/pQo6YMZop

我认为这个解决方案非常优雅,因为我们使用了官方的 react-router API,它也用于路由器中的路径匹配.我们也不使用 window.location 在这里,所以如果你也导出原始组件,测试/模拟会很容易.

I think that this solution is quite elegant because we use official react-router API which is also used for path matching in router. We also don't use window.location here so testing / mocking will be easy if you export also raw component.

这篇关于如何在父路由组件中获取参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆