从URL参数获取ID react.js

时间:2020-03-30 18:29:16

标签: reactjs

我正在尝试从我在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>

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

尝试

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

请参阅https://tylermcginnis.com/react-router-url-parameters/