【问题标题】:React Router not keeping query反应路由器不保持查询
【发布时间】:2018-04-03 11:35:07
【问题描述】:

我正在发送带有我的链接的查询,如下所示:

 <Link to={{ 
     pathname: `/forum/${this.state.mainCategoryName}/${category.name}`, 
     query: { subcatid: category.id} }
   }
 >
  {category.name}
 </Link>

这工作得很好,我可以像这样渲染值:

 this.props.location.query.subcatid

但是,一旦我刷新页面或以某种方式以除使用链接之外的其他方式进入页面,则不会包含查询。

我怎样才能做到这一点?

我的路由器是这样的:

<Route 
  exact={true} 
  path="/forum/:forumcatid/:forumsubcatid" 
  render={
    (routeProps) => ( 
      <ForumThreads {...routeProps} {...this.props} /> 
    )
  } 
/>

【问题讨论】:

  • 原因是查询是由导致导航的组件提供的,但是在刷新期间,该组件不再导致重定向。但是如果将查询参数添加到url中,则刷新后即可获取
  • 查看这个问题,了解如何从 react-router v4 自定义 withRouter 以提供查询参数stackoverflow.com/questions/48993247/…
  • 谢谢,我真的不想在我的 URL 中包含 id,这就是我尝试将其作为道具发送的原因。正如我所提到的,当通过链接进入页面时,这工作正常,但不是其他方式。也许没有解决办法。
  • 唯一可能的解决方案是在卸载时将接收到的查询参数存储在 localStorage 中
  • 感谢您的回答。我想我只是将 id 作为参数添加到 url,简单的 oldschool :) 我只是认为会有一种更聪明的方法来保持干净的 URL。

标签: reactjs router


【解决方案1】:

也许可以在ForumThreads 中与ComponentDidMount 核对。因为整页刷新后你没有pass查询,它就在那里。

ComponentDidMount(){
 // here check
 // this.props.location.search 
 // to see if it allready contains some query strings inside url 
 // and then do your magic :)
}

【讨论】:

    猜你喜欢
    • 2017-08-14
    • 2017-06-26
    • 2017-05-07
    • 1970-01-01
    • 2018-06-09
    • 2017-02-09
    • 2022-01-16
    • 2016-07-06
    • 1970-01-01
    相关资源
    最近更新 更多