欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

如何在React应用中通过react-router-dom实现外部路由控制?

最编程 2024-08-08 10:01:48
...

一、前言

相信常用 react 开发的小伙伴对于 react-router 这个库一定不会陌生,最近我在封装 axios 时遇到一个问题:如果 access_token 过期了,希望能够跳转到登陆页,这该怎么实现?
解决这个问题之前,让我们先来复习一下 react-router 的基础用法。

二、基础用法

1、安装


在项目目录下的控制台键入:

yarn add react-router-dom

2、配置


在我们的项目根目录,也就是 /src/App.js 中导入 BrowserRouter 和 Route 组件:

import React from 'react';
import { BrowserRouter, Route } from 'react-router-dom';

import Login from './pages/login';
import Home from './pages/home';

function App() {
  return (
    <div className="App">
      <BrowserRouter>
        {/* BrowserRouter 只能有一个根节点,所以这里用个 div 包裹 */}
        <div>
          <Header />
          {/* exact 表示精确匹配
            * 如果不加,则 /home 会同时匹配成功 / 和 /home ,导致渲染两个组件
            */}
          <Route path='/' exact component={ Login } />
          <Route path='/home' exact component={ Home } />
          <Footer />
        </div>
      </BrowserRouter>
    </Provider>
  );
}

export default App;


3、使用 Link 组件跳转


例如在 Home 组件中我们需要点击按钮跳转至 Login 组件:

import React, { PureComponent } from 'react';
import { Link } from 'react-router-dom';

class Home extends PureComponent {
  render () {
    return (
      <div className='home'>
        <Link to='/'>
          <Button>click</Button>
        </Link>
      </div>
    );
  }
};

export default Home;


4、在 js 中控制跳转


事实上很多真实业务中并不会仅仅做一个跳转,我们希望能够在 js 执行到一定阶段时跳转:

import React, { PureComponent } from 'react';
import { Link } from 'react-router-dom';

class Home extends PureComponent {
  render () {
    return (
      <div className='home'>
        <Button onClick={ this.handleClick }>click</Button>
      </div>
    );
  }
 
  handleClick = () => {
    // ... your logic
    this.props.history.push('/');
  }
};

export default Home;


5、动态路由传参


在 /src/App.js 中新增 Detail 组件:

import React from 'react';
import { BrowserRouter, Route } from 'react-router-dom';

import Login from './pages/login';
import Home from './pages/home';
import Home from './pages/detail';

function App() {
  return (
    <div className="App">
      <BrowserRouter>
        <div>
          <Header />
          <Route path='/' exact component={ Login } />
          <Route path='/home' exact component={ Home } />
           {/* :id 表示可以匹配类似 /detail/1 的路由 */}
          <Route path='/detail/:id' exact component={ Home } />
          <Footer />
        </div>
      </BrowserRouter>
    </Provider>
  );
}

export default App;

因此我们使用 Link 组件的时候可以动态地传递参数值:

<Link to={ `/detail/${item.id}` }></Link>

在 Detail 组件中获取参数只要:

this.props.match.params.id


5、非动态路由传参


有时候传递的参数不是 id 值并且比较多的情况(一般不会出现,都用 redux 了...),我们会使用url params 的方式传参。
先把 /src/App.js 中的路由改回来:

<Route path='/detail' exact component={ Home } />

然后传递参数的时候只要:

<Link to={ `/detail?key1=${value}&key2=${value2}` }></Link>

我们在 /src/statics/js/utils.js 中封装好的工具方法 getUrlParam:

/**
 * 获取地址栏参数
 * @param name 参数名称
 */
export const getUrlParam = (name) => {
  const regx = new RegExp(`(^|&)${name}=([^&]*)(&|$)`);
  const result = window.location.search.substr(1).match(regx);
  return result ? decodeURIComponent(result[2]) : null;
};

获取参数:

import * as utils from ‘/src/statics/js/utils’;

const value1 = utils.getUrlParam(value1);
const value2 = utils.getUrlParam(value2);


3、配合 react-loadable 使用

在我们使用 react-loadable 的时候,通常是这么写的:

import React from 'react';
import { BrowserRouter, Route } from 'react-router-dom';

// 这里改为从 loadable.js 中加载
import Login from './pages/login/loadable';
import Home from './pages/home/loadable';

function App() {
  return (
    <div className="App">
      <BrowserRouter>
        <div>
          <Header />
          <Route path='/' exact component={ Login } />
          <Route path='/home' exact component={ Home } />
          <Footer />
        </div>
      </BrowserRouter>
    </Provider>
  );
}

export default App;

这时候,我们的代码就会神奇的报错:push is not a Function ,在 componentDidMount 里 console 一下 this.props 会发现里面并没有 history 属性。
这里需要引入 withRouter 方法,它把不是通过路由切换过来的组件中,将react-router 的 history、location、match 三个对象传入props对象上:

// /src/home/index.js
import React, { PureComponent } from 'react';
import { withRouter, Link } from 'react-router-dom';

class Home extends PureComponent {
  render () {
    return (
      <div className='home'>
        <Button onClick={ this.handleClick }>click</Button>
      </div>
    );
  }
 
  handleClick = () => {
    // ... your logic
    this.props.history.push('/');
  }
};

// 使用 withRouter 包装 Home 组件
export default withRouter(Home);


四、在组件外部控制路由跳转

props 只有在组件中才能使用,我们的项目中通常会希望在组件外部能够控制路由跳转,这里提供以下几种解决方案:

1、传值


例如在使用 react-thunk 配合 react-redux 处理异步数据时,我们一般会统一使用一个 actionCreator 来处理异步代码,派发 action ,既然没有,那我们就传过去:

// /src/home/index.js
import React, { PureComponent } from 'react';
import { connect } from 'react-redux';
import * as actionCreators from './store';
import { withRouter, Link } from 'react-router-dom';

class Home extends PureComponent {
  render () {
    // 从 this.props 中取 history
    const { handleClick, history } = this.props;
    return (
      <div className='home'>
        {/* 将 history 传给方法 handleClick */}
        <Button onClick={ () => handleClick(history) }>click</Button>
      </div>
    );
  }
};

const mapState = (state) => ({});

const mapDispatch = (dispatch) => ({
  handleClick (history) {
    // 派发 actionCreators.getData() 时同时传入 history
    dispatch(actionCreators.getData(history));
  }
});

export default connect(mapState, mapDispatch)(withRouter(Home));
// /src/home/store/actionCreators.js
import axios from 'axios';
import * as constants from "./constants";

export const getData = (history) => {
  return (dispatch) => {
    axios.get('Your Interface Path').then(result => {
      const res = result.data;
      if (res.status === 'success') {
        // ... your logic
        // 跳转
        history.push('/');
      }
    }).catch(err => {
      console.log('error:', err);
    });
  };
};


2、无法传参的情况

很多时候并不会这么顺心如意,我们无法传参,例如:我们封装 localStorage 储存access_token 时,当 access_token 失效,我们希望能够跳回 Login 页。
localStorage 具体封装详见我的另一篇博客:
https://www.jianshu.com/p/ed1cc98916b3

// /src/statics/js/storage.js
get (key, callback = () => {}) {
  let dataJSON = localStorage.getItem(key);
  if(this.isNotExist(dataJSON)) {
    return null;
  }
  let data = JSON.parse(dataJSON);
  if(this.isNotExist(data.expired)) {
    return data.value;
  }
  if(this.isOutPeriod(data)) {
    this.del(key);
    // localStorage 失效时执行回调
    callback();
    return null;
  }
  return data.value;
}
// /src/statics/js/history.js
// hack,在组件外部使用导航
const createHistory = require('history').createBrowserHistory;

export default createHistory();
// /src/App.js
import React from 'react';
import { Provider } from 'react-redux';
import store from './store';
// 不再使用 BrowserRouter 组件,而使用 Router 组件
import { Router, Route } from 'react-router-dom';
// 引入刚刚创建的 history
import history from './statics/js/history';
import { Globalstyle } from './style';
import 'antd/dist/antd.css';

import Header from './common/header';
import Footer from './common/footer';
import Login from './pages/login/loadable';
import Home from './pages/home/loadable';

function App() {
  return (
    <Provider className="App" store={ store }>
      <Globalstyle />
      {/* 不再使用 BrowserRouter 组件,而使用 Router 组件,同时传入 history */}
      <Router history={ history }>
        <div>
          <Header />
          <Route path='/' exact component={ Login } />
          <Route path='/home' exact component={ Home } />
          <Footer />
        </div>
      </Router>
    </Provider>
  );
}

export default App;
// /src/statics/js/api.js
import axios from 'axios';
import { message } from 'antd';
import { localstorage } from './utils';
// 引入刚刚创建的 history
import history from './history';

// ... other logics
let build = (url, {method, params, data, headers, responseType}) => {
  let token = localstorage.get('token', () => {
    message.warning('access_token 已失效,请重新登陆!');
    // 跳转
    history.push('/');
  });
  let config = {
    url,
    method,
    params,
    headers: token ? extend({'x-access-token': token}, headers) : headers,
    data,
    responseType
  }
  return axios(extend(config, DEFAULT_AXIOS_CONFIG));
};
// ... other logics

注意:React Router 中文文档 中介绍了一种方法,

// your main file that renders a Router
import { Router, browserHistory } from 'react-router'
import routes from './app/routes'
render(<Router history={browserHistory} routes={routes}/>, el)
// somewhere like a redux/flux action file:
import { browserHistory } from 'react-router'
browserHistory.push('/some/path')

在 react-router@4 中实测无效,应该是版本更新去除了这一方法,而中文文档更新有所延迟

四、结语

react-router@4 中推荐我们使用 BrowserRouter 组件,而我们的以上实现 又用回了 Router 组件,看了大佬的博客,推荐我们自己看源码写一个 BrowserRouter 组件,我没能实现,后面有机会自己尝试以下。同学们知道或是有兴趣的也可以自己试试,欢迎讨论!
希望这篇文章能够帮助同学们成功爬坑,如果对您有所帮助,请关注、点赞并收藏,有其他问题也可以留言或私信,欢迎讨论!