【问题标题】:In React Router, how do you pass route parameters when using browser history push?在 React Router 中,使用浏览器历史推送时如何传递路由参数?
【发布时间】:2016-12-05 08:25:08
【问题描述】:

使用较新版本的 React Router,如果使用 browserHistory.push() 进行转换,如何将参数传递给要转换的路由?如果 browserHistory 不允许,我愿意使用其他方式进行转换。我看到在 React Router 中我最顶层的子组件中有 this.props.routeParams 但我似乎无法在转换时从上一个路由中填充我想要的值。

【问题讨论】:

    标签: react-router


    【解决方案1】:

    现在你会做这样的事情

    history.push({
      pathname: '/about',
      search: '?the=search',
      state: { some: 'state' }
    })
    

    这是API documentation的链接

    【讨论】:

    • 从props获取的location对象内
    • 在下一页使用this.props.location.state.some访问状态
    • 这在 React Router V4 中仍然有效吗?
    【解决方案2】:

    对于 react router v4,我们可以这样做:

    const history = useHistory();
     history.push({
          pathname: "/create-opinion/"+user,
          state:{  username:userName}
        };
    

    并简单地从其他组件中获取它:

    const history = useHistory();
    

    然后获取用户名:

    const username = history.location.state.username;
    

    别忘了从 react-router-dom 导入 useHistory

    如果你还没有安装 react-router-dom 输入:

    $ npm install --save react-router-dom
    

    【讨论】:

      【解决方案3】:

      如果要传递路径参数,可以按如下方式进行。我正在使用示例组件 Merchant

      定义路线

      <Route exact path="/merchant/:id" render={(props) => <Merchant id={props.match.params.id}/>} />
      

      定义历史

      const history = createBrowserHistory({
          basename:''
      })
      

      使用参数添加到历史记录

      history.push(`/merchant/${id}`)
      

      【讨论】:

        猜你喜欢
        • 2018-05-16
        • 2017-12-29
        • 2017-03-17
        • 2021-11-01
        • 2022-10-12
        • 2017-08-17
        • 2017-12-14
        • 2017-03-17
        • 2021-08-25
        相关资源
        最近更新 更多