react 中 实现类似 vue中 keep-live的效果
网上案列多达4-5种 这里列下用到的3种
- 手动按照需求 (粗暴 直接)
- 使用插件 react-activation ( 在原有路由添加)
- 使用插件 react-router-cache-route (改动原本路由渲染标签)
手动设置
设置缓存或者全局状态管理 , 然后在生命周期里就进行数据恢复 (简单 粗暴 每个人可以按照自己的逻辑去写)
插件1 react-activation
// 使用 keep-live 缓存
方案之 react-activation
import React from 'react';
import { HashRouter, Route, Switch, Link } from 'react-router-dom';
import Routers from "../../router"
import KeepAlive, { AliveScope } from 'react-activation'
const App = () => (
<HashRouter>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/Demo">Demo</Link>
</li>
<li>
<Link to="/User">User</Link>
</li>
</ul>
<Switch>
<AliveScope>
{Routers.map((item, index) => {
return <Route key={index} path={item.path} exact render={props => {
console.log(item)
return <KeepAlive><item.component cache {...props} /></KeepAlive>
}} />
})
}
{/* // 所有错误路由跳转页面 */}
{/* <Route component={NotFound} /> */}
</AliveScope>
</Switch>
</HashRouter >
);
export default App;
插件1 react-router-cache-route
// 使用 keep-live 缓存
方案之 react-router-cache-route
import React from 'react';
import Routers from "../../router"
import { HashRouter as Router, Link } from 'react-router-dom'
import CacheRoute, { CacheSwitch } from 'react-router-cache-route'
const App = () => (
<Router>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/Demo">Demo</Link>
</li>
<li>
<Link to="/User">User</Link>
</li>
</ul>
<CacheSwitch>
{Routers.map((item, index) => {
return <CacheRoute key={index} path={item.path} exact render={props => {
console.log(item)
return <item.component cache {...props} />
}} />
})
}
{/* // 所有错误路由跳转页面 */}
{/* <CacheRoute component={NotFound} /> */}
</CacheSwitch>
</Router >
);
export default App;
最后
以上就是动听红牛最近收集整理的关于keep-live for reactreact 中 实现类似 vue中 keep-live的效果的全部内容,更多相关keep-live内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复