如何在父路由组件中获取params

Sle*_*vin 8 reactjs react-router react-redux

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

这是我的条目,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>
Run Code Online (Sandbox Code Playgroud)

那是我的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))
Run Code Online (Sandbox Code Playgroud)

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

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

我可以将项目的ID保存在我的ProjectPage组件内的商店中,但我认为这会有点混乱,特别是因为URL实际上有信息 - 所以我为什么要在商店里写一些东西呢?

另一种(不好?)的方法是解析对象的位置由我自己一开始的ID,但我觉得有一个react-router/ react-router-redux办法在这一点上,我已经忽略得到PARAMS.

hin*_*nok 11

@Kyle从技术角度解释了问题.我将专注于解决该问题.

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

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

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

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

1使用 matchPath

// 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;
}
Run Code Online (Sandbox Code Playgroud)

2 articleId在渲染中使用

{articleId && (
  <h1>You selected article with id: {articleId}</h1>
)}
Run Code Online (Sandbox Code Playgroud)

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

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

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