编程语言
首页 > 编程语言> > javascript-React Router向下滚动新页面

javascript-React Router向下滚动新页面

作者:互联网

我在使用react-router ^ 2.4.1时遇到了一个问题,如果我在主页上向下滚动,然后转到新页面,它也将向下滚动,而不是位于顶部(预期行为).

我正在使用这个入门包:react-webpack-node,而我的routes.jsx看起来像这样

import React from 'react'
import { Route, IndexRoute } from 'react-router'
import cookie from 'react-cookie'

import App from 'containers/App'
import HomePage from 'containers/HomePage'
import WaitingListPage from 'containers/WaitingListPage'
import NotFoundPage from 'containers/NotFoundPage'
import SupportPage from 'containers/SupportPage'

/*
 * @param {Redux Store}
 * We require store as an argument here because we wish to get
 * state from the store after it has been authenticated.
 */
export default (store) => {
  const hasQueueToken = (nextState, replace, callback) => {
    if (cookie.load('queueToken')) {
      replace({
        pathname: `/waiting-list/${cookie.load('queueToken')}`,
        state: { nextPathname: nextState.location.pathname }
      })
    }
    callback()
  }

  return (
    <Route path='/' component={App}>
      <IndexRoute component={HomePage} />
      <Route path='/w_ref/:ref' component={HomePage} />
      <Route path='/waiting-list/:token' component={WaitingListPage} />
      <Route path='/waiting-list' onEnter={hasQueueToken} component={WaitingListPage} />
      <Route path='/support' component={SupportPage} />
      <Route path='/terms-and-conditions' component={TermsConditions} />
      <Route path='/privacy-policy' component={PrivacyPolicy} />
      <Route path='*' component={NotFoundPage} />
    </Route>
  )
}

解决方法:

从2.0.0版开始,React Router不包括滚动状态管理.

推荐的方法是使用react-router-scroll用滚动行为装饰路由器,如in this example所示:

import { applyRouterMiddleware, browserHistory, Router } from 'react-router';
import useScroll from 'react-router-scroll';

/* ... */

ReactDOM.render(
  <Router
    history={browserHistory}
    routes={routes}
    render={applyRouterMiddleware(useScroll())}
  />,
  container
);

标签:reactjs,redux,react-router,javascript
来源: https://codeday.me/bug/20191026/1940401.html