【问题标题】:get param from url in react-router [duplicate]从反应路由器中的url获取参数[重复]
【发布时间】:2017-09-05 01:05:48
【问题描述】:

现在我正在做“脏”拆分以从 url 获取任何 id。我不知道如何使用反应路由器,我做了这样的事情

this.__isEdit = (this.props.history.location.pathname.indexOf('edit') > -1)

const pathnameArr = this.props.history.location.pathname.split('/')
this.__todoId = pathnameArr[pathnameArr.length - 2] //get second last arr

我的一条路线

<Route exact path='/admin/ad/:id/edit' component={createTodoComponent} />

无论如何我可以改进它的代码?

【问题讨论】:

  • 你在使用 Redux 吗?
  • 你使用哪个版本的 React-router
  • @ShubhamKhatri v4.
  • @DaleFrancis 是的,但我猜这与 redux 无关?

标签: javascript reactjs redux


【解决方案1】:

因此,对于您的组件,您需要使用“react-router-dom”中的 withRouter 方法包​​装它,然后您可以从 this.props 中获取任何参数

import { withRouter } from 'react-router-dom'

const component = ({match}) => {
    const id = match.params.id

    return (
        <span>{id}</span>
    )
}

export default withRouter(component)

或者如果你想用 React 组件类来做

import { withRouter } from 'react-router-dom'

class NewComponent extends Component {
    render() {
        const {match} = this.props
        const id = match.params.id

        return (
            <span>{id}</span>
        )
    }
}

export default withRouter(NewComponent)

【讨论】:

  • 这是纯组件如果我的组件是一个类怎么办?
  • 是一样的。您只需将组件类传递给 withRouter 然后执行 this.props.match.params.id
【解决方案2】:

react 路由器参数在连接组件内的 this.props.params 上可用。

【讨论】:

  • 不。不在反应路由器 v4 中
猜你喜欢
  • 2015-11-03
  • 1970-01-01
  • 2020-09-23
  • 1970-01-01
  • 2017-06-14
  • 2016-09-15
  • 2020-10-02
  • 2019-08-11
相关资源
最近更新 更多