react-router路由跳转,react-router5.x 的配置及其页面跳转方法和js跳转方法

https://blog.csdn.net/sinat_37255207/article/details/90745207

上次用react-router 的时候 还是3.x 很久不用 已经到react-router5.x 了

废话不多说 上代码

配置

react: ^16.8.6,

react-dom: ^16.8.6,

react-router: ^5.0.0,

react-router-dom: ^5.0.0,

路由配置

用HashRouter还是BrowserRouter 自己来定 两者区别 两种路由的区别

import { HashRouter,BrowserRouter, Route, Link, Switch } from "react-router-dom";
 
....
//用HashRouter还是BrowserRouter 自己来定
<BrowserRouter>
          <Link to="/a" black'}}>
              <div>点击跳转到a</div>
              </Link>
              <Link to="/b" black'}}>
              <div>点击跳转到b</div>
              </Link>
              <Switch>
                <Route exact path='/' component={App1}/>
                
                <Route path='/a' component={App1}/>
                <Route path='/b' component={App2}/>
          <Switch/>
        </BrowserRouter> ....

路由组件 js路由跳转

//路由组件 js路由跳转
 
constructor(props){
        super(props);
        
}
//有history记录跳转
this.props.history.push('/register');
//无history记录跳转
this.props.history.replace('/register');
//返回
this.props.history.goBack();
 

一般组件withRouer js路由跳转

import { withRouer } from "react-router-dom";
 
class Demo extends React.PureComponent {
    ...
    //暴露时加了高阶组件withRouer ,这样一般组件内部才能操作this.props.history
    demo1=()=>{
       
         this.props.history.push('/**');
    }
}
 
//withRouer高阶组件 必须
export default withRouer(Demo);

  

拓展 https://www.jianshu.com/p/336770af0047

X

请尝试网页搜索