使用 React Router 根据查询参数重新加载具有状态的路由 [英] Reload a route that has state based on query params using React Router

查看:98
本文介绍了使用 React Router 根据查询参数重新加载具有状态的路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个路由,它根据查询参数在构造函数中设置状态.由于 React Router 没有根据查询参数进行路由的选项,即使查询参数发生变化,React Router 也会将其视为相同的路由.

I have a route that sets state in the constructor based on the query parameters. Since React Router doesn't have the option to route based on query parameters, even if the query parameters change, React Router treats it as the same route.

例如,React Router 将 http://example.com/http://example.com/?page=2 视为相同的路由.如果我从第二页重定向到第一页,构造函数就不会再次运行.但是,我需要再次运行构造函数以重置状态.

For example, React Router treats http://example.com/ and http://example.com/?page=2 as the same route. If I redirect from the second page to the first page, the constructor doesn't run again. However, I need the constructor to run again to reset the state.

有没有办法强制 React Router 重新加载路由?

Is there a way to force React Router to reload a route?

这是一个有效的解决方案,但它非常笨拙.

Here's a solution that works, but it's very hacky.

function redirect(path) {
  browserHistory.push('/fake-path');
  setTimeout(_ => {
    browserHistory.replace(path);
  }, 0);
}

...


<Router history={browserHistory}>
  <Route path="/" component={AppRoute}>
    <IndexRoute component={HomeRoute}/>
    ...
    <Route path="fake-path" component={_ => null}/>
  </Route>
</Router>;

有更好的解决方案吗?

推荐答案

您可以使用组件的方法 componentWillReceiveProps 来检查查询参数的变化.

You can use the method componentWillReceiveProps of your component to check the query params changes.

// AppRoute.js
componentWillReceiveProps(nextProps) {
   if (this.props.location.query.page !== nextProps.location.query.page) {
      // handle query parameter change here
   }
}

这篇关于使用 React Router 根据查询参数重新加载具有状态的路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆