【问题标题】:get id from url params react.js从 url 参数 react.js 获取 id
【发布时间】:2020-07-11 05:01:04
【问题描述】:

我正在尝试从我在 react.js 中使用的 url 参数获取 id。这是我的代码

componentDidMount() {
    let {id} = this.props.params
}

但我没有定义,我控制台记录了参数,我得到一个空数组

如何获取参数?

这是路由器代码

<BrowserRouter>
    <Navbar />
      <Switch>
        <Route exact path="/" component={home} ></Route>
        <Route exacth path="/details/:id" component={details} />
      </Switch>
</BrowserRouter>

【问题讨论】:

  • 尝试使用withRouter react-router HOC 将传递的路由器对象连接到组件并做很多其他事情。
  • 您有机会查看Route 的文档吗?看起来以下道具在基础级别暴露了match, location, history
  • componentDidMount 在哪里?是在details 组件内吗?

标签: reactjs


【解决方案1】:

根据https://stackoverflow.com/a/45069909/6809926,您将能够使用this.props.match.params 而不是this.props.params 访问您的ID:

componentDidMount() {
    let {id} = this.props.match.params
}

【讨论】:

  • 我收到此错误 TypeError: Cannot read property 'params' of undefined 看来我将 props 作为空数组获取
  • 在你的路线中你写:exacth 而不是exact 可能是什么?您是否还尝试仅打印 this.props 以查看其内容?
【解决方案2】:

试试

componentDidMount () {
    const { id } = this.props.match.params
}

https://tylermcginnis.com/react-router-url-parameters/

【讨论】:

    【解决方案3】:
    componentDidMount () {
            const { id } = this.props.match.params.id
        }
    

    console.log(id) 在我的情况下可以恢复 id。没有 .id,我得到一个对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-05
      • 2018-12-11
      • 1970-01-01
      • 2018-08-27
      • 2014-05-12
      • 2016-02-14
      相关资源
      最近更新 更多