这里有没有你想要的react-router

前端之家收集整理的这篇文章主要介绍了这里有没有你想要的react-router前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

由于React Router 4.0已经正式发布,所以该博文分React Router 和 React Router 4.0 进行分类讨论!该博文会持续更新中,欢迎大家一起讨论与补充!

我相信用过react一般都用过react-router,那就很有必要说说用react-router实现的一些常用功能了,比如组件按需加载、用户登录验证、刷新当前路由。。。在这篇文章中,我将列出一些react-router使用小技巧,希望每个读者都能至少从中学到一个有用的技巧!

一、按需加载

React Router:使用 getComponent + require.ensure 实现按需加载

getComponent 相比以前的 component 属性,这个方法是异步的,也就是当路由匹配时,才会调用这个方法

  1. require.ensure(dependencies,callback,chunkName)

require.ensure 是 webpack 提供的方法,这也是按需加载的核心方法。第一个参数是依赖的模块数组,第二个是回调函数,该函数调用时会传一个require参数,第三个是模块名,用于构建时生成文件时命名使用

实现按需加载核心代码如下:

  1. import React,{ Component } from 'react'; // react核心
  2. import { Router,Route,Redirect,IndexRoute,browserHistory } from 'react-router';
  3.  
  4. /**
  5. * (路由根目录组件,显示当前符合条件的组件)
  6. *
  7. * @class Roots
  8. * @extends {Component}
  9. */
  10. class Roots extends Component {
  11. render() {
  12. return (
  13. <div>{this.props.children}</div>
  14. );
  15. }
  16. }
  17.  
  18. const history = browserHistory;
  19.  
  20. // 首页
  21. const home = (location,cb) => {
  22. require.ensure([],require => {
  23. cb(null,require('./Home').default);
  24. },'home');
  25. }
  26.  
  27. const RouteConfig = (
  28. <Router history={history}>
  29. <Route path="/" component={Roots}>
  30. <IndexRoute getComponent={home} />
  31. <Route path="/home" getComponent={home} />
  32. <Route path="/login" component={login} />
  33. <Redirect from="*" to="/home" />
  34. </Route>
  35. </Router>
  36. );
  37.  
  38. export default RouteConfig;

React Router 4.0:使用 babel-plugin-Syntax-dynamic-import + react-loadable 实现按需加载

首先确保已安装 babel-plugin-Syntax-dynamic-import react-loadable,未安装请先安装:

  1. npm i -D babel-plugin-Syntax-dynamic-import
  2.  
  3. npm i -S react-loadable

实现按需加载核心代码如下:

  1. import React,{ Component } from 'react';
  2. import { BrowserRouter,HashRouter,Switch,Redirect} from 'react-router-dom';
  3. import createBrowserHistory from 'history/createBrowserHistory'
  4. const history = createBrowserHistory();
  5.  
  6. // 按路由拆分代码
  7. import Loadable from 'react-loadable';
  8.  
  9. const loadingComponent = ({ isLoading,error }) => {
  10. // Handle the loading state
  11. if (isLoading) {
  12. return <div>Loading...</div>;
  13. }
  14. // Handle the error state
  15. else if (error) {
  16. return <div>Sorry,there was a problem loading the page.</div>;
  17. }
  18. else {
  19. return null;
  20. }
  21. };
  22.  
  23. const Index = Loadable({
  24. loader: () => import('./Index'),loading: loadingComponent
  25. });
  26.  
  27. const Home= Loadable({
  28. loader: () => import('./Home'),loading: loadingComponent
  29. });
  30.  
  31. const Login= Loadable({
  32. loader: () => import('./Login'),loading: loadingComponent
  33. });
  34.  
  35. /**
  36. * (路由根目录组件,显示当前符合条件的组件)
  37. *
  38. * @class Roots
  39. * @extends {Component}
  40. */
  41. class Roots extends Component {
  42. render() {
  43. return (
  44. <div>{this.props.children}</div>
  45. );
  46. }
  47. }
  48.  
  49. let Router = process.env.NODE_ENV !== 'production' ? BrowserRouter : HashRouter;
  50.  
  51. const RouteConfig = (
  52. <Router history={history}>
  53. <Switch>
  54. <Route path="/" exact component={Index} />
  55. <Route path="/home" component={Home} />
  56. <Route path="/login" component={Login} />
  57. <Redirect from='' to="/" />
  58. </Switch>
  59. </Router>
  60. );
  61.  
  62. export default RouteConfig;

二、实现登录验证

React Router:利用 Route 的 onEnter 钩子在渲染对象组件前做拦截操作实现登录验证;

  1. import React,'home');
  2. }
  3.  
  4. // 登录验证
  5. const requireAuth = (nextState,replace) => {
  6. if(true) { // 未登录
  7. replace({
  8. pathname: '/login',state: { nextPathname: nextState.location.pathname }
  9. });
  10. }
  11. }
  12.  
  13. const RouteConfig = (
  14. <Router history={history}>
  15. <Route path="/" component={Roots}>
  16. <IndexRoute getComponent={home} onEnter={requireAuth} />
  17. <Route path="/home" getComponent={home} onEnter={requireAuth} />
  18. <Route path="/login" component={login} />
  19. <Redirect from="*" to="/home" />
  20. </Route>
  21. </Router>
  22. );
  23.  
  24. export default RouteConfig;

React Router4.0:在 Route 的 render 属性添加一个函数实现登录验证;

实现登录验证核心代码如下:

  1. import React,loading: loadingComponent
  2. });
  3.  
  4. /**
  5. * (路由根目录组件,显示当前符合条件的组件)
  6. *
  7. * @class Roots
  8. * @extends {Component}
  9. */
  10. class Roots extends Component {
  11. render() {
  12. return (
  13. <div>{this.props.children}</div>
  14. );
  15. }
  16. }
  17.  
  18. // 登录验证
  19. function requireAuth(Layout,props) {
  20. if (true) { // 未登录
  21. return <Redirect to="/login" />;
  22. } else {
  23. return <Layout {...props} />
  24. }
  25. }
  26.  
  27. let Router = process.env.NODE_ENV !== 'production' ? BrowserRouter : HashRouter;
  28.  
  29. const RouteConfig = (
  30. <Router history={history}>
  31. <Switch>
  32. <Route path="/" exact component={Index} />
  33. <Route path="/home" component={props => requireAuth(Home,props)} />
  34. <Route path="/login" component={Login} />
  35. <Redirect from='' to="/" />
  36. </Switch>
  37. </Router>
  38. );
  39.  
  40. export default RouteConfig;

三、实现点击左侧菜单刷新当前组件

React Router:利用 Route 的 createElement 钩子实现点击左侧菜单刷新当前组件;

实现点击左侧菜单刷新当前组件核心代码如下:

  1. import React,'home');
  2. }
  3.  
  4. // 此处为要点击刷新的组件
  5. const arr = [
  6. home
  7. ];
  8.  
  9. // 开关优化
  10. let onOff =false;
  11.  
  12. // 页面强制刷新,如果需要强制刷新在路由中添加onChange事件以及在组件数组添加
  13. const createElement=(component,props) =>{
  14. if (props.children && onOff || props.children && arr.includes(props.routes.slice(-1)[0].getComponent)) {
  15. let children = Object.assign({},props.children,{key : `${window.location.pathname}` + new Date().getTime()})
  16. props = { ...props,children };
  17. onOff = false;
  18. }
  19. return React.createElement(component,props)
  20. }
  21.  
  22. const onChange = (props,next) => {
  23. onOff = true
  24. console.log(`${next.location.pathname}`,'change');
  25. }
  26.  
  27. const RouteConfig = (
  28. <Router history={history} createElement = {createElement}>
  29. <Route path="/" component={Roots}>
  30. <IndexRoute getComponent={home} />
  31. <Route path="/home" getComponent={home} />
  32. <Route path="/login" component={login} />
  33. <Redirect from="*" to="/home" />
  34. </Route>
  35. </Router>
  36. );
  37.  
  38. export default RouteConfig;

欢迎大家一起讨论react-router使用小技巧,该博文会持续更新!

猜你在找的React相关文章