useParams 可以在 App.js 内部使用吗? [英] Can useParams be able to use inside App.js?

查看:79
本文介绍了useParams 可以在 App.js 内部使用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

美好的一天,希望我没有打扰你们.

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

我有这样的路径

localhost:3000/Project-1/todo-1

和这样的路由切换

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

<小时>

预期产出

当浏览器在示例路径中时,我期望 App.js 也可以通过使用 useParams获取 params 对象,但显示为空.我是否误用了钩子?谢谢你的回答.


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.

我确实使用了 useLocation 返回类似路径的东西,但这不是我的目标,它应该是类似

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

使用 useParams 返回,以便于提取项目和待办事项值

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

推荐答案

我相信 Route 向它渲染的组件注入了 props,所以你应该能够直接从 match<Todo 中的/code> 道具:this.props.match.params.

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:

  • 路由组件为 this.props.match
  • 路由渲染为 ({ match }) => ()
  • 将子级路由为 ({ match }) => ()
  • withRouter as this.props.match
  • matchPath 作为返回值

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

这仅适用于在路由上渲染的组件,即组件Route是渲染,或 DOM 树更下方的子组件.如果 App.js 正在渲染路由器,它将没有它.

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.

如果您需要对根 App.js 中的路由参数执行某些操作,您可以使用渲染道具将它包装在一个路由中,使用未指定的路径以便匹配所有路由.只要确保这在任何 Switch 组件之外呈现,因为开关返回第一个匹配项,而不是所有匹配项.

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.

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

这篇关于useParams 可以在 App.js 内部使用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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