blog icon indicating copy to clipboard operation
blog copied to clipboard

react 路由跳转方式

Open huangshuwei opened this issue 5 years ago • 0 comments

前言

这篇文章介绍 react-router-dom路由的几种跳转方式

示例中版本要求:react-router-dom 5.x

使用路由的 Link组件方式跳转

适用场景:点击菜单跳转

使用 Link 组件方式跳转相当于点击 <a />标签方式跳转,因为Link 组件会渲染成<a href="/home">首页</a>

代码示例:

import { BrowserRouter as Router,Link} from 'react-router-dom';

...
render(){
   return (
      <Router>
        <ul>
          <li>
             <Link to="/home">首页</Link>
          </li>
          <li>
            <Link to="/order">订单</Link>
          </li>
        </ul>
      </Router>
    )
}
...

使用路由Redirect组件方式跳转

适用场景:重定向跳转,如登录后跳转

代码示例:

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

...
render(){
   if (isLogin){
      
       return <Redirect to='/home' />;
    }else{
      
          return <Redirect to='/login' />;
    }
}
...

使用路由withRouter 高级组件方式跳转

适用场景:通过 js 手动跳转

withRouter 能够将路由信息的matchlocationhistory通过 props的方式传递给当前包装的组件

代码示例:

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

class demoComp extends React.Component{

    constructor(props) {
        super(props);
        
    }
    
    goToHomePage = ()=>{

        this.props.history.push('/home')
    }
    
    render() {
    
        return (
            
            <button onClick={this.goToHomePage}>跳转首页</button>
        )
    }
}

export default withRouter(demoComp)

--完--

huangshuwei avatar Sep 27 '19 06:09 huangshuwei