在反应中使用 useParams 钩子 [英] Using the useParams hook in react
问题描述
我正在学习 useParams hook in react.我有一个这样的网址,需要能够从中提取字母9.
http://localhost:3010/9/solution
我该怎么做?
我假设你正在使用 react router,如果你定义了这样的路由,例如:
<关于/></路线>
请注意,您使用此 :id 符号定义路径,这意味着 id 将是此特定情况下的参数.然后你创建一个Link组件
关于
在你的组件中,在这个例子中是 about 组件,你可以像这样使用钩子:
function About() {const { id } = useParams();返回 (<div><h2>现在显示帖子{id}</h2>
);}
如果你想检查结果,我有这个代码沙箱 https://codesandbox.io/s/react-router-basic-nv8pn
I am learning useParams hook in react. I have a url like this and need to be able to extract the letter 9 from it.
http://localhost:3010/9/solution
How can I go about this ?
I'm assuming you're using react router, if you define a route like this for example:
<Route path="/:id/about">
<About />
</Route>
Notice that you define the path with this :id notation, that means that the id will be the param in this specific case. Then you create a Link component
<Link to="/2/about">About</Link>
And in your component that in this example is the about component you can use the hook like this:
function About() {
const { id } = useParams();
return (
<div>
<h2>Now showing post {id}</h2>
</div>
);
}
I have this code sandbox if you want to check the result https://codesandbox.io/s/react-router-basic-nv8pn
这篇关于在反应中使用 useParams 钩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!