React 中保存页面状态,在react中实现vue的keep-alive,React Activation

今天有个业务需求,在列表页筛选查询条件后,进入详情页,返回列表页时,筛选条件还存在。

选中了React Activation插件,使用如下:

这是参考文档:react-activation/README_CN.md at d08219cba1fd3bc2ddd18b382eac656f1826d65d · CJY0208/react-activation · GitHub

1、安装

yarn add react-activation

2、在App.js页面引入AliveScope

import { AliveScope } from "react-activation";
import React from 'react'
import Laout from './pages/Laout'
import { Switch, Redirect } from 'react-router-dom'
import RouteViews from './router/index'
import { ConfigProvider } from 'antd';
import zhCN from 'antd/lib/locale/zh_CN';
import moment from 'moment';
import 'moment/locale/zh-cn';
import { AliveScope } from "react-activation";
moment.locale('zh-cn');


function App () {
  const isLogin = sessionStorage.getItem('token') || ''
  return isLogin ? (
    
      
) : } export default App;

 

3、在渲染路由时添加缓存KeepAlive 

import React, { Component } from 'react';
import { Redirect, Route, Switch } from "react-router-dom";
import routes from './config'
import KeepAlive from "react-activation";

export default class RouterView extends Component {
  render () {

    //let { routes } = this.props;	//取到传进来的路由表
    let routerArr = routes.filter(item => !item.redirect); //非重定向的数据过滤出来
    let redirectArr = routes.filter(item => item.redirect).map(item => )

    const renderRoutes = (route) => {

      return route.map(item => {
        if (item.children && item.children.length > 0) {
          return renderRoutes(item.children)
        } else {
          return item.path === "/" ? null : ( {
            return 
          }} />)
        }
      }).concat(redirectArr)
    }


    return (
      
        {renderRoutes(routerArr)}
      
    )
  }
}

你可能感兴趣的:(react)