因为项目页面不多,并且已经写完,没有用到redux,所以不需要为了保存数据专门再引入redux,就直接使用了react-keeper的方式处理,快捷方便。
react-keeper项目地址:https://github.com/vifird/react-keeper
一、引入react-keeper
npm install react-keeper
二、路由配置修改
原来
import { Route, Switch, BrowserRouter as Router } from 'react-router-dom';
<Router basename="m/ershouche">
<Switch>
<Route exact path="/" component={Cardlist}></Route>
<Route exact path="/cardetail/:infoid" component={Cardetail}></Route>
<Route component={Cardlist} />
</Switch>
</Router>
现在
import { Route, HashRouter, CacheLink } from 'react-keeper';
<HashRouter>
<div>
<Route index cache path="/>" component={Cardlist}/>
<Route cache component={Cardlist}></Route>
<Route path="/cardetail/:infoid" component={Cardetail}></Route>
</div>
</HashRouter>
三、跳转方法修改
原来
this.props.history.push(`/cardetail/${infoid}`);
现在
setCookie('detail', 'true');
Control.go(`/cardetail/${infoid}`);
需要引入Control
import { Control } from 'react-keeper'
四、详情页参数获取方式修改
原来
let infoid = this.props.match.params.infoid
现在
let infoid = this.props.params.infoid
五、返回方法修改
原来
const goBack = useCallback(() => {
if(document.referrer=="") {
window.location.href = "https://xxxx.com/m/xxxxxx";
} else {
window.history.go(-1);
return;
}
}, []);
现在
const goBack = useCallback(() => {
let detail = JSON.parse(getCookie('detail'));
if(detail) {
Control.go(-1)
} else {
window.location.href = "https://xxxx.com/m/xxxxxx";
}
}, []);
之前是通过document.referrer===‘’的方式判断是否是分享过来直接打开的详情页链接,后来发现有兼容性问题,所以改成通过cookie判断的方式,这样从详情页返回列表页就不会重新渲染了。