在开发后台管理页面的时候,会遇到缓存Tab页面数据的需求。在开发时也希望能够使用数组驱动的方式控制Tab页的缓存,并且使用API进一步控制tab页缓存或者其他页缓存。
之前关注的开发者新写了一个模块,正好满足了我的需求
react-activation:https://github.com/CJY0208/react-activation
原理应该是把Alive组件下的dom挂载到Provider组件的display:none的一个节点,当路由切回来时,在从provider中找之前挂在的alive dom。作者已经帮我们实现了,用就是了。

alive.gif
用法
使用react-activation提供的KeepAlive组件包裹你的页面组件,控制KeepAlive的when值
作者提供了demo:可关闭的路由 tabs 示例
但这个是API控制的,我更希望使用一个[]数据来驱动tabs和页面缓存
数据驱动
改变数据
使用redux管理这个数据,建立了一个tabs数组,我希望tabs和页面是否被缓存,都是响应这个数组。
我写了2个action去操作这个tabs,新增,和删除
// 新增tab
export function pushTab({url,title}) {
const { tabs } = getState()
push(url)
// 在tabs没有的加上
if (tabs.findIndex(item => item.url === url) < 0) {
tabs.push({
url,
title
})
dispatch({
type: ActionTypes.SET_TABS,
tabs: tabs
})
}
}
// 关闭这个tab
export function removeTab({ url }) {
const { tabs } = getState()
let newTabs = tabs.filter(item => item.url !== url)
push(newTabs[newTabs.length - 1].url)
dispatch({
type: ActionTypes.SET_TABS,
tabs: newTabs
})
}
响应
然后我希望redux中的tabs的变化,能触发我的视图更新,用React-Redux提供的connect将store中的tabs绑定到组件上。当tabs发生变化时,我的缓存组件就能响应到,从而改变keepAlive的when值,实现缓存控制
import React from 'react'
import KeepAlive from 'react-activation'
import { connect } from 'react-redux'
export default function withAliveComponent(Component) {
// 包裹一层KeepAlive
const wrapAliveComponent = function (props) {
const id = props.location.pathname
// 当url存在与tabs数组中,保持缓存
return <KeepAlive id={id} when={props.tabs.findIndex(item => item.url === id) >= 0}>
<Component {...props} />
</KeepAlive>
}
// 绑定store中的tabs
return connect(state => {
return {
tabs: state.tabs
}
})(wrapAliveComponent)
}
更多action
当组件已经能响应tabs的变化时,添加更多功能【关闭/关闭其他/关闭到右侧/关闭全部】,通过写不同的action操作tabs数组就可以了

array.gif
