現狀:目前從商品詳情頁返回到商品列表頁,還需要再去請求服務數據,還需要用戶再去等待獲取數據的過程,這樣用戶體驗非常不好,
遇到的問題:
1:如何將數據緩存,
2:如何獲取和保存列表滑動的高度,
3:判斷商品列表頁的上一個頁面是什么?
如果是從搜索頁進到商品列表頁的話我們需要清除緩存,獲取接口數據,
如果是商品詳情頁返回到商品列表頁的話就用緩存數據,並且滑到到上次瀏覽的位置。
一:數據緩存
使用react全家桶reducers保存數據
1 dispatch({ 2 type: types.PRODUCT_LIST, 3 productlist: oldList.concat(data.result), 4 totalPage: data.totalPage, 5 curPage: page, 6 totalCount: data.totalCount 7 });
二:獲取和保存列表滑動的高度
在商品列表頁銷毀方法里記錄滑動高度
1 componentWillUnmount(){ 2 var top = $(document).scrollTop(); 3 window.sessionStorage.setItem("top",top); 4 window.sessionStorage.setItem("isUseCacheProductList",false); 5 6 }
三:判斷商品列表頁的上一個頁面是什么
在商品詳情頁離開時劫持路由,判斷如果是去商品列表頁的話,就設置標識為true。
以下每一步都很關鍵
商品詳情頁代碼:
import {Router} from 'react-router'
Product.contextTypes = {
store: React.PropTypes.object,
router: React.PropTypes.object.isRequired
};
componentWillMount() { /* 發起請求 */ this.props.actions.initState(); this.context.router.setRouteLeaveHook( this.props.route, this.routerWillLeave ) }
routerWillLeave( nextLocation ){ console.log("路由跳轉---"+ nextLocation.pathname); if(nextLocation.pathname == '/product/list'){ window.sessionStorage.setItem("isUseCacheProductList",true); } }
在商品列表頁獲取isUseCacheProductList這個標識,如果為true,說明是商品詳情頁返回來的,那么久使用緩存數據,
商品列表頁代碼:
渲染函數里自動滑動到上次瀏覽位置
render() { const {store} = this.context; var isUseCache = window.sessionStorage.getItem("isUseCacheProductList"); var top = window.sessionStorage.getItem("top"); if(isUseCache == "true"){ $("html,body").animate({scrollTop: top + "px"}, 0); } }
這里判斷是否需要請求接口數據還是使用緩存數據
componentDidMount() { const {store} = this.context; var isUseCache = window.sessionStorage.getItem("isUseCacheProductList"); if(isUseCache != "true"){ this.props.actions.findProductList("", 1, store.getState().productTodos.pageSize, this.state.categoryId, this.state.keyword, [],isShowInStock,slectString,store.getState().commonTodos.userTypeCode); } }
商品列表頁銷毀時記錄滑動距離,重置 isUseCacheProductList 標識為false。
componentWillUnmount(){ //window.addEventListener('scroll', this.handleScroll); var top = $(document).scrollTop(); window.sessionStorage.setItem("top",top); window.sessionStorage.setItem("isUseCacheProductList",false); console.log("距離頂部距離="+top) }