问题描述
我正在使用 ConnectedRouter from 'react-router-redux'
新页面加载时,旧页面位置保持不变;我希望它滚动到顶部。我尝试添加不同的 scroll to top functionality,但我怀疑使用 react-router-redux 会使这些修复不兼容。
有人用 react-router-redux 实现滚动到顶部吗? 谢谢。
App.js 的一部分
...
<Provider store={this.props.store}>
<ConnectedRouter history={this.props.history}>
<div className="container-fluid main-page grey-background">
<Header />
<ScrollToTop />
<Switch>
<Route path="/meals/:startDate?" component={MealsPage} />
<Route path="/faqs" component={FAQsPage} />
<Route path="/discounts" component={discountsPage} />
<Route path="/survey/consent" component={SurveyConsentPage} />
<Route path="/survey" component={SurveyPage} />
<Route path="/blog/:postName" component={BlogPost} />
<Route path="/blog" component={BlogPostListPage} />
<Route exact path="/services" component={ServicesList} />
<Route path="/services/:serviceSlug/:task?" component={ServicePage} />
<Route path="/credits" component={CreditsPage} />
<Route path="/privacy" component={PrivacyPage} />
<Redirect from="/" to="/meals" />
<Redirect from="/specials" to="/discounts" />
</Switch>
<Footer />
</div>
</ConnectedRouter>
</Provider>
</Fragment>
...
ScrollToTop.js
import * as React from "react";
import { withRouter } from "react-router";
// Scroll restoration using https://github.com/ReactTraining/react-router/issues/2019#issuecomment-299576935
class ScrollToTop extends React.Component {
componentDidUpdate(prevProps) {
const oldLocation = prevProps.location
const newLocation = this.props.location
if (newLocation !== oldLocation) {
const newPathComponents = newLocation.pathname.split('/')
const oldpathComponents = oldLocation.pathname.split('/')
const samePage = [0,1,2].every((i) => newPathComponents[i] === oldpathComponents[i])
if (! samePage) {
this.scrollToTop()
}
}
}
scrollToTop() {
window.scrollTo(0,0)
}
render() {
return null
}
}
export default withRouter(ScrollToTop)
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)