可以使用useParams在App.js内部吗?

huangapple go评论61阅读模式
英文:

Can useParams be able to use inside App.js?

问题

当浏览器处于示例路径时,我期望的是 App.js 也可以通过使用 useParams 来获取参数对象,但显示为空。我是否错误使用了这个钩子?谢谢您的回答。

英文:

Good day, hoping that I am not bothering you guys.


Details

I have a path like this

localhost:3000/Project-1/todo-1

and Switch of Route like this

<Route path='/:project/:todo' component={Todo} />

Expected Output

When browser is in the example path, what I expected is App.js can also get params object by using useParams but shows empty. Did I misuse the hook? Thank you for the answers.


Additional Details

I did use useLocation that returns something like path but that is not my aim, it should be something like

params: { 
  project: 'Project-1', 
  todo: 'todo-1 '
}

that is returned using useParams for ease of extraction of project and todo values

答案1

得分: 2

我相信 Route 会将属性注入到它渲染的组件中,因此你应该能够直接从 Todo 组件中的 match 属性中获取它:this.props.match.params

在各个地方都可以访问匹配对象:

  • Route 组件中作为 this.props.match
  • Route 渲染为 ({ match }) => ()
  • Route 子组件中作为 ({ match }) => ()
  • 使用 withRouter 作为 this.props.match
  • matchPath 作为返回值

这仅适用于在路由上渲染的组件,即 Route 渲染的组件或 DOM 树下的子组件。如果 App.js 渲染了路由,则无法获得它。

如果你需要在根级别的 App.js 中处理路由参数,你可以将它包装在一个路由中,路径未指定,以便匹配所有路由,然后在你的路由器中使用渲染属性。只需确保这个路由在任何 Switch 组件之外渲染,因为 switches 返回第一个匹配项,而不是所有匹配项。

<Route
  render={({ match }) => {
    console.log('match', match);
    // 使用 `match` 属性执行所需操作,例如 `match.params`
    return null; // 返回 null 表示实际上不应该渲染任何内容
  }}
/>
英文:

I believe Route injects props to components it renders, so you should be able to pull it straight from the match prop within Todo: this.props.match.params.

You’ll have access to match objects in various places:

  • Route component as this.props.match
  • Route render as ({ match }) => ()
  • Route children as ({ match }) => ()
  • withRouter as this.props.match
  • matchPath as the return value

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

This only works for components rendered within a router on a route, i.e. the component a Route is rendering, or a child component further down the DOM tree. If App.js is rendering the router it won't have it.

If you need to do something with route params in the root App.js you can wrap it in a route, with unspecified path so it matches all routes, in your router using the render prop. Just ensure this is rendered outside any Switch components though as switches only return the first match, not all matches.

&lt;Route
  render={({ match }) =&gt; {
    console.log(&#39;match&#39;, match);
    // do what you need with the `match` prop, i.e. `match.params`
    return null; // return null to indicate nothing should actually be rendered
  }}
/&gt;

huangapple
  • 本文由 发表于 2020年1月4日 00:15:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/59581817.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定