reactjs прокрутка вверх не работает после рендеринга - PullRequest
1 голос
/ 24 февраля 2020

Я довольно новичок в reactjs и хочу перейти к началу страницы после изменения маршрута. Я испробовал почти все возможности для достижения этой цели, но не повезло. Я потратил более 2 дней, и я решил опубликовать это здесь постыдно, так как есть миллиарды дубликатов. Я использую реагирует: v16.12, редукс: v4, реактив-маршрутизатор-дом: v5.1

Я пробовал что-нибудь в этих сообщениях:

Прокрутите до верхней части страницы после рендеринга в реакции. js

https://gist.github.com/romanonthego/223d2efe17b72098326c82718f283adb

реакции-маршрутизатор каждый переход

Это мое приложение. js (я знаю, что его нужно немного реорганизовать)

import React, { Component } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import jwt_decode from "jwt-decode";
import setAuthToken from "utils/setAuthToken";
import {
  setCurrentUser,
  logoutUser,
  getNotifications
} from "actions/authActions";
import { clearCurrentProfile } from "actions/profileActions";

// import { ApolloProvider } from 'react-apollo';
// import { ApolloClient } from 'apollo-client';
// import { HttpLink } from 'apollo-link-http';
// import { InMemoryCache } from 'apollo-cache-inmemory';
import store from "store";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import ScrollIntoView from "../appUtils/ScrollIntoView";


// Check for token
if (localStorage.jwtToken) {
  // Set auth token header auth
  setAuthToken(localStorage.jwtToken);
  // Decode token and get user info and exp
  const decoded = jwt_decode(localStorage.jwtToken);
  // Set user and isAuthenticated
  store.dispatch(setCurrentUser(decoded));
  store.dispatch(getNotifications(decoded.id));
  // Check for expired token
  const currentTime = Date.now() / 1000;
  if (decoded.exp < currentTime) {
    // Logout user
    store.dispatch(logoutUser());
    // Clear current Profile
    store.dispatch(clearCurrentProfile());
    // Redirect to login
    window.location.href = "/login";
  }
}

class App extends Component {
  static propTypes = {
    auth: PropTypes.object.isRequired
  };

  isClient = () => typeof window !== "undefined";

  render() {
    const { auth } = this.props;
    const user = auth && auth.user ? auth.user : null;

    const adminRoutes = () => (
      <div>
        <Switch>
          <PrivateRoute exact path="/admin" component={Admin} />

          <PrivateRoute
            exact
            path="/admin/credential"
            component={UserCredentialList}
          />

          <PrivateRoute
            exact
            path="/admin/user/credential/:id"
            component={UserCredential}
          />

          <PrivateRoute
            exact
            path="/admin/deactivate"
            component={UserDeactivateList}
          />

          <PrivateRoute
            exact
            path="/admin/user/deactivate/:id"
            component={UserDeactivate}
          />
        </Switch>
      </div>
    );

    return (
      <div className={styles["app-wrapper"]}>
        <Router>
          <ScrollIntoView>
          <Navbar />
          <React.Fragment>
            <div className={styles["content-wrapper"]}>
              <Route exact path="/" component={Landing} />
                <Switch>
                  <Route exact path="/register" component={Register} />
                  <Route exact path="/login" component={Login} />
                  <Route exact path="/thank-you" component={ThankYouPage} />
                  <Route exact path="/sign-out" component={SignoutPage} />
                  <Route
                    exact
                    path="/password/recover"
                    component={RecoverPassword}
                  />
                  <Route
                    exact
                    path="/password/reset/:userId/:token"
                    component={UpdatePassword}
                  />
                  <Route
                    exact
                    path="/notifications"
                    component={Notifications}
                  />
                </Switch>

                <Switch>
                  <PrivateRoute
                    exact
                    path="/profiles"
                    component={ProfilesLandingPage}
                  />
                  <PrivateRoute
                    exact
                    path="/specialists"
                    component={SpecialistsPage}
                  />
                  <PrivateRoute
                    exact
                    path="/profile/:handle"
                    component={Profile}
                  />
                  {user && user.isAdmin && adminRoutes()}
                  <PrivateRoute exact path="/dashboard" component={Dashboard} />
                  {/* <Switch>
                <PrivateRoute exact path="/messages" component={Messages} />
              </Switch> */}
                  <PrivateRoute
                    exact
                    path="/create-profile"
                    component={CreateProfile}
                  />
                  <PrivateRoute
                    exact
                    path="/edit-profile"
                    component={EditProfile}
                  />
                  <PrivateRoute
                    exact
                    path="/edit-account"
                    component={EditAccount}
                  />
                  <PrivateRoute
                    exact
                    path="/change-password"
                    component={ChangePassword}
                  />
                  <PrivateRoute
                    exact
                    path="/add-experience"
                    component={AddExperience}
                  />
                  <PrivateRoute
                    exact
                    path="/add-education"
                    component={AddEducation}
                  />
                  {/* <PrivateRoute
                      exact
                      path="/add-payment"
                      component={AddPayment}
                    />
                    <PrivateRoute
                      exact
                      path="/update-payment"
                      component={UpdatePayment}
                    /> */}
                  <PrivateRoute exact path="/public-qa" component={PostsPage} />
                  <PrivateRoute
                    exact
                    path="/post/edit/:id"
                    component={PostEdit}
                  />
                  <PrivateRoute
                    exact
                    path="/ask-question"
                    component={PostForm}
                  />
                  <PrivateRoute
                    exact
                    path="/create-case"
                    component={CreateCase}
                  />
                  <PrivateRoute
                    exact
                    path="/contact-messages"
                    component={ContactMessagesPage}
                  />
                  <PrivateRoute
                    exact
                    path="/contact-messages/:id"
                    component={ContactMessageItem}
                  />
                  {/* <Switch>
                  <PrivateRoute
                    exact
                    path="/cases"
                    component={CaseLandingPage}
                  />
                </Switch> */}
                  <PrivateRoute
                    exact
                    path="/your-cases"
                    component={YourCasesPage}
                  />
                  <PrivateRoute
                    exact
                    path="/case/:id"
                    component={CaseDetails}
                  />
                  <PrivateRoute
                    exact
                    path="/post/:id"
                    component={PostDetails}
                  />
                </Switch>

                <Route exact path="/not-found" component={NotFound} />
                <FooterRoutes />
            </div>
          </React.Fragment>
          <Footer />
          </ScrollIntoView>
        </Router>
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    auth: state.auth
  };
}

export default connect(mapStateToProps)(App);

, и это мой ScrollIntoView. js util :

import React, { Component } from 'react';
import { withRouter } from 'react-router';

class ScrollIntoView extends Component {
  componentDidUpdate(prevProps) {
    if (this.props.location !== prevProps.location) {
      window.scrollTo(0,0);
      console.log('hello world')
    }
  }

  render() {
    return this.props.children
  }
}

export default withRouter(ScrollIntoView)

Итак, я попытался использовать useEffect (), пакет oaf и историю, но не повезло. Я добавил console.log ('hello'); в компонент ScrollIntoView, он срабатывает при изменении маршрута, но не прокручивается вверх. Интересно, что-то перезаписано? Любые советы и рекомендации будут высоко оценены. Спасибо за ваше время и внимание.

1 Ответ

0 голосов
/ 24 февраля 2020

Вы проверили, есть ли окно?

if (typeof window !== 'undefined') {
  window.scrollTo(0,0);
} 
...