使用react-router-dom优雅的实现页面(路由)跳转, 而且保持当前页面状态

做web页面, 无论你是使用Jquery, 还是使用React, 都会用到页面跳转功能, 当然谁都知道的方法是直接使用location跳转, 如下:

window.location.href="target_page"

但如果你使用 React + Redux 的话, 这样的跳转就相当于页面跳出, 会重新加载css/js, 而且前一个页面的状态(store里面存的state就清空为默认状态了)就没了, 这导致两个问题:
  1. 想要获取前一个页面的状态无法获取, 你可以通过跳转的url传递参数, 如: window.location.href="target_page?arg1=xxx&agr2=yyy"
  2. 按后退按键, 返回前一个页面, 那个页面也要重新加载css/js/数据

这显然不是我们想要的, 也就不是纯属的单页面应用了. 而且这也不是React官方推荐使用的方法

我上网找来找去, 有说用push, 但我没成功

this.props.history.push("/target_page") //报错: this.props.history is undefined

最后还是万能的stackoverflow找到了解决方法, 其实可以使用 react-router-dom 的Redirect功能, 优雅的实现页面跳转, 代码如下


import { Redirect } from 'react-router-dom';

// ... your class implementation

handleOnClick = () => {
  // some action...
  // then redirect
  this.setState({redirect: true});
}

render() {
  if (this.state.redirect) {
    return <Redirect push to="/sample" />; //or <Redirect push to="/sample?a=xxx&b=yyy" /> 传递更多参数
  }

  return <button onClick={this.handleOnClick} type="button">Button</button>;
}

或者这样写Redirect

<Redirect to={{
  pathname: '/login',
  search: '?utm=your+face',
  state: { referrer: currentLocation }
}}/>


使用上面的方法就可以简单方面的进行跳转了, 而且全局store状态还维持着不会改变, 下一个页面也不会重新加载/css/js, 才这是真正的单页面应用嘛!!!!!

参考:

https://stackoverflow.com/questions/29244731/react-router-how-to-manually-invoke-link

https://reacttraining.com/react-router/web/api/Redirect

猜你喜欢

转载自blog.csdn.net/cen_cs/article/details/77977385
今日推荐