项目采用的是react+typescript框架。有一个业务需求:
用户在信息填写页面,填写了很多信息,点击提交按钮,到下一个页面后,再返回,这些信息都变成空了,
用户需要再填写一遍。
这样繁琐,会不会流失掉很多用户?所以理想状态下,就是页面返回后,这些信息还在。
所以就用到了react-keeper
1、react-keeper是什么?
React-Keeper是React生态里一款较新的开源路由库,由国内团队开发,借鉴了React-Router 4很多特点,不过灵活性、实用性都强于React-Router很多,而且兼容React-Router常用用法,其文档和代码可以参见https://github.com/vifird/react-keeper。
2、缓存页面信息
如果想把某个页面的信息缓存下来,路由切换的时候,这些信息不丢失,可以采用下面的写法
import { HashRouter,Route } from 'react-keeper';
<HashRouter>
<div>
<Route exact path="/" component={Product}/>
<Route cache path="/insure" component={Insure}/>
</div>
</HashRouter>
其中,会把Insure这个页面的信息缓存下来。
3、路由跳转
A页面想跳B页面,js如下:
import {Control} from 'react-keeper';
Control.go('/pay');
如果想带参数,如下
Control.go('/pay?orderId='+orderId);
使用Link,跳转如下:
import {Link} from 'react-keeper';
<Link to="/pdf">
《购买须知》
</Link>
react-keeper在功能上类似vue的keep-alive。
4、局限性
使用react-keeper做路由功能时,页面来回切换时,不会触发页面组件的componentWillMount,componentDidMount这些生命周期,只会触发componentWillUpdate、componentDidUpdate、render、componentWillReceiveProps这些生命周期,如果在componentWillUpdate、componentDidUpdate、render这些周期里面setState,会陷入无限循环。在componentWillReceiveProps里面设置比较好。