javascript 使用 React Router 从 url 获取参数值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49668455/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 08:42:38  来源:igfitidea点击:

get parameter value from url using React Router

javascriptreactjsapiurlreact-router-v4

提问by kurniawan26

I want to get the id value from this React Router:

我想从这个 React Router 获取 id 值:

<BrowserRouter basename="/api">
    <Switch>
        <Route path="/pm" exact component={PaymentMethod}/>
        <Route path="/pw" exact component={PaymentWeb}/>
        <Route path="/rg" exact component={Registrasi}/>
        <Route path="/bonus/:id" exact component={BonusScreen}/>
        <Route path="/hb" exact component={HistoryBonus}/>
    </Switch>
</BrowserRouter>

in my BonusScreenI tried to print the value by using this :

在我的BonusScreen我试图通过使用这个打印值:

const userId = this.props.match.id;
console.log(this.userId);

from the browser I try to access the URL like this:

从浏览器我尝试访问这样的 URL:

bonus/NGO628567652201

But it always returned undefined.
How can I fix this ?

但它总是返回undefined
我怎样才能解决这个问题 ?

回答by Alcides Bezerra

In case of anyone having this problem. The correct would be:

如果有人遇到这个问题。正确的应该是:

const userId = this.props.match.params.id;

05/2020 UPDATE USING REACT ROUTER V4 AND HOOKS

05/2020 更新使用 React Router V4 和 Hooks

import { useParams } from 'react-router-dom';

//Then inside your component
const { id } = useParams();

回答by Shan

You can try this

你可以试试这个

const id = this.props.computedMatch.params.id

const id = this.props.computedMatch.params.id