4.React 之react-router-dom

2,322 阅读4分钟

在React中使用react-router-dom路由

使用React构建的单页面应用,要想实现页面间的跳转,首先想到的就是使用路由。在React 使用react-router-dom进行路由的开发

安装

首先进入项目目录,使用npm安装react-router-dom

npm install react-router-dom --save-dev 
or
yarn add react-router-dom -D

基本操作

然后我们新建两个页面,分别命名为“home”和“detail”。在页面中编写如下代码:

// home.js
import React from 'react';

export default class Home extends React.Component {
    render() {
        return (
            <div>我是houme</div>
        )
    }
}
// detail.js
import React from 'react';
export default class Detail extends React.Component {
    render() {
        return (
            <div>我是detail</div>
        )
    }
}

App组件中使用

import { HashRouter, Route } from 'react-router-dom'
function App() {
  return (
    <Provider store={store}>
      <HashRouter>
        <Header/>
        <div>
          {/* 如果是/detail/id 这种形式,path=/detail/:id 叫做动态路由,获取参数时获取props.match.params 即可  */}
          {/* 如果页面通过/detail?id=xxx 这种形式,patch即原始的/detail 获取参数应该从props中的location search 中解析,比较麻烦*/}
          <Route exact component={Home} path="/"/>
          <Route exact component={Login} path="/login"/>
          <Route exact component={Detail} path="/detail/:id"/>
          <Route exact component={Write} path="/write"/>
        </div>
      </HashRouter>
    </Provider>
  )
}

这样就设置好路由了,在使用跳转时可以这么使用,包裹一个Link组件设置to来进行跳转

import { Link } from 'react-router-dom'

class List extends PureComponent {
  render() {
    return (
      <div className="list">
        {
          this.props.articleList.map((item, index) => {
            return (
              <Link to={'/detail/' + item.get('id')} className="list-item" key={index}>
                <div className="list-info">
                  跳转详情
                </div>
              </Link>
            )
          })
        }
        <div className="load-more" onClick={this.props.getMoreList}>阅读更多</div>
      </div>
    )
  }
}

通过函数跳转

先我们需要修改router.js中的两处代码:

...
import {HashRouter, Route, Switch, BrowserRouter} from 'react-router-dom';
...
<HashRouter history={BrowserRouter}>
...

跳转时则通过props的history来push跳转

有些场景下,重复使用push或a标签跳转会产生死循环,为了避免这种情况出现,react-router-dom提供了replace。在可能会出现死循环的地方使用replace来跳转:

export default class Home extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
        return (
            <div>
                <a href='#/detail'>去detail</a>
                <button onClick={() => this.props.history.push('detail')}>通过函数跳转</button>
            </div>
        )
    }
}

路由传参

动态路由

//如果是/detail/id 这种形式,path=/detail/:id 叫做动态路由,获取参数时获取props.match.params 即可
//如果页面通过/detail?id=xxx 这种形式,patch即原始的/detail 获取参数应该从props中的location search 中解析,比较麻烦*/}
<Route exact path="/detail/:id" component={Detail}/>

此外还可以通过push函数隐式传参。

import React from 'react';

export default class Home extends React.Component {
    constructor(props) {
        super(props);
    }
    
    render() {
        return (
            <div>
                <a href='#/detail/3'>去detail</a>
                    <button onClick={() => this.props.history.push({
                        pathname: '/detail',
                        state: {
                            id: 3
                        }
                })}>通过函数跳转</button>
            </div>
        )
    }
}

获取既可以通过 this.props.history.location.state获取

嵌套路由

嵌套路由的适用场景还是比较多的,接下来就来介绍一下实现方法。 首先在Vue中实现嵌套路由,只需要将配置文件写成children嵌套,然后在需要展示子路由的位置加上即可。React中应该如何实现呢?其实原理和Vue类似,只需要在父级路由中包含子路由即可。这样说可能很多同学会一头雾水,直接上代码(不使用上面的例子): 首先定义父级组件MainLayout

import React from 'react';
import './MainLayout.scss';
const { Header, Sider, Content } = Layout;
export default class MainLayout extends React.Component {
    render() {
        return (
            <div className='main-layout'>
                父组件
            </div>
        );
    }
}

然后定义子组件Home:

import React from 'react';
function Home(props) {
    return (
        <div>
            子组件
        </div>
    )
}

export default Home;

然后将它们添加进路由router.js,并且关联父子关系:

import React from 'react';
import {HashRouter, Route, Switch} from "react-router-dom";
import Home from '../pages/Home/Home';
import MainLayout from '../layout/MainLayout';

const BasicRouter = () => (
    <HashRouter>
        <Switch>
            <Route path="/index" component={
                <MainLayout>
                  <Route exact path="/" component={Home}/>
                  <Route exact path="/index" component={Home}/>
                  <Route path="/index/home" component={Home}/>
                </MainLayout>
             }/>
        </Switch>
    </HashRouter>
);


export default BasicRouter;

Redirect

redirect组件用于重定向到某个路由,通常可以用来判断跳转,也可以用函数式来跳转路由

import React, { PureComponent } from 'react'
import { connect } from 'react-redux'
import { actionCreator } from './store'
import { Redirect } from 'react-router-dom'

class Login extends PureComponent {
  render() {
    if (this.props.isLogin) {
      return <Redirect to="/"/>
    }
    return (
      <div className="login-wrap" data-flex="main:center">
        <div className="login-box">
          <h4 className="t-center">Login 登录</h4>
          <input placeholder="输入用户名" ref={(input) => this.username = input}/>
          <input placeholder="输入密码" type="password" ref={(input) => this.password = input}/>
          <button onClick={() => this.props.login(this.username, this.password)}>登录</button>
        </div>
      </div>
    )
  }
}

const mapStateToProps = (state) => ({
  isLogin: state.getIn(['login', 'login'])
})


const mapDispatchToProps = (dispatch) => ({
  login(usernameEl, passwordEl) {
    dispatch(actionCreator.login(usernameEl.value, passwordEl.value))
  }
})

export default connect(mapStateToProps, mapDispatchToProps)(Login)

相关连接

最近在学习react开发,整理几篇笔记方便自己查询使用,下面是连接地址

1.React 之 react-transition-group

2.React之 redux、react-redux、redux-thunk

3.React 之 immutable 和 redux-immutable

4.React 之react-router-dom

5.React 之 react-loadable

6.React 基础记录

7.React 使用less等预处理器配置