reactjs - 如何获取父路由组件中的参数

标签 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>

这就是我的 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

我想向我的 ProjectList 添加一个 ID 属性以突出显示当前选定的项目。

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

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

最佳答案

@Kyle 从技术角度很好地解释了问题。 我将只专注于解决该问题。

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

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.

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

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;
}

2 在渲染中使用articleId

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

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

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

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

关于reactjs - 如何获取父路由组件中的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45487779/

相关文章:

javascript - 获取错误 : "react.createclass is not a function"

css - 如何将变量传递给 React 中的内联 css 函数

javascript - 在 React 中,如何在 n 秒后以编程方式滑动(使用转换)到另一条路线?

java - dropwizard 应用程序中的配置更改以与 React browserHistory 配合使用

javascript - 如何将 react-tether 与 react-dom createPortal 一起使用,以便能够根据它所绑定(bind)的组件来设置绑定(bind)组件的样式?

javascript - 移动到 React Native 中选定的页面

javascript - React-JS : Uncaught TypeError: Cannot read property 'router' of undefined

reactjs - react 包装器 : React does not recognize the `staticContext` prop on a DOM element

javascript - 如何使用 redux 将联系人添加到我的联系人状态对象?

reactjs - Redux Toolkit RTK 查询 useMutation 并保留缓存数据