【问题标题】:What's the proper way to pass url parameters to a react-router's Link component?将 url 参数传递给 react-router 的 Link 组件的正确方法是什么?
【发布时间】:2020-11-10 16:50:10
【问题描述】:

到目前为止,我一直在使用链接组件时手动替换 url 参数的名称,例如:

const userIdParam = ':userId'

const routes = {
   userDetails: `/users/${ userIdParam }`
}

<Link to={{
   pathname: routes.userDetails.replace(userIdParam, user.id)
}}/>

React 路由器是否支持将参数作为道具传递给 to 对象或类似的东西?我正在寻找类似于以下内容的内容:

const routes = {
   userDetails: `/users/:userId`
}

<Link to={{
   pathname: routes.userDetails,
   props: {
      userId: user.id
   }
}}/>

我一直在浏览打字和文档,但真的找不到任何东西。

【问题讨论】:

    标签: reactjs react-router react-router-dom react-router-v5


    【解决方案1】:

    是的。 如果你想四处导航,那么你可以使用:

    <Link to="/redirect-to-this-url"></Link>
    

    以防万一,你想通过 react-router 传递道具然后这样做。

    // Initial Page
    <Link to={{
        pathname: "redirected-route",
        state: {
            variable: value    // pass the extracted url params here
        }
    }}
    </Link>
    

    以 Link 状态传递的对象可以通过以下方式访问:

    // Redirected component
    this.props.location.state    // { variable: "value" }
    

    【讨论】:

    • 有人明白这个吗?
    • @SebastianThomas 需要帮助吗?
    猜你喜欢
    • 2019-12-05
    • 2018-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-24
    • 2016-03-19
    • 1970-01-01
    • 2021-11-22
    相关资源
    最近更新 更多