【问题标题】:get parameter value from url using React Router使用 React Router 从 url 获取参数值
【发布时间】:2018-09-15 01:05:28
【问题描述】:

我想从这个 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>

在我的BonusScreen 中,我尝试使用这个来打印值:

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

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

bonus/NGO628567652201

但它总是返回undefined
我该如何解决这个问题?

【问题讨论】:

  • 你标记了这个api,但上面写着“不要使用:用你的意思的库标记,[api-design],或者其他合适的东西。”。你应该解决这个问题。

标签: javascript reactjs api url react-router-v4


【解决方案1】:

如果有人遇到此问题。 正确的是:

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

05/2020 更新使用 REACT 路由器 V4 和 Hooks

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

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

【讨论】:

    【解决方案2】:

    你可以试试这个

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-03
      • 1970-01-01
      • 2018-12-08
      相关资源
      最近更新 更多