问题描述
- 问题1:
- 滚动一个长页面A
- 点击一个Link 进入到另外一个长页面B
- 长页面B没有滚动到顶部
- 问题2:
- scroll down a long page
- click a link - page 2 will be correctly scrolled to the top
- click Back
- click the same or any other link without scrolling
- observe the new page is not scrolled to the top
- https://github.com/taion/scroll-behavior/issues/15#issuecomment-198339485
期望情况
- A到B,B页面滚动到顶部
- B返回到A时页面停留在原来位置
解决方案
- 利用react-router提供的onUpdate事件
<Router onUpdate={() => window.scrollTo(0, 0)} history={createHashHistory()}>
...
</Router>
- https://github.com/ReactTraining/react-router/issues/2019
- 缺点可以达到期望一,但是无法到达期望二
- 引入react-router-scroll
- 达到期望一,二
- 缺点:引入三方包,得看用法
- 利用history.listen监听每次router改变,根据location.action分类处理(推荐)
hashHistory.listen(location => {
setTimeout(() => {
//浏览器前进后退
if (location.action === 'POP') { return }
// Use setTimeout to make sure this runs after React Router's own listener
window.scrollTo(0, 0);
})
})