简体   繁体   English

类型错误:无法读取未定义的属性“历史记录”

[英]TypeError: Cannot read property 'history' of undefined

I'm trying to redirect the user to the login page when the /logout routes is hit.当 /logout 路由被命中时,我试图将用户重定向到登录页面。 The auth is working (jwt token is removed, but the app fails to redirect to /login.身份验证正在运行(jwt 令牌已删除,但应用程序无法重定向到 /login。

Also If I do to / the app crashes as well.另外,如果我这样做 / 应用程序也会崩溃。

On the Login route I uses withRouter from the react-router-dom package wih this I can access the this.props.history.push('/redirect_to_a_new_path') , but when I try to wrap the App component with withRouter method it crashes as well.在登录路线上,我使用来自 react-router-dom package 的 withRouter,我可以访问this.props.history.push('/redirect_to_a_new_path') ,但是当我尝试使用withRouter方法包装 App 组件时,它崩溃为出色地。

Please help!请帮忙!

Here is the github repo :这是github 回购

App.js应用程序.js

import React, { Component } from "react";
import {
  BrowserRouter as Router,
  Route,
  Switch,
  withRouter
} from "react-router-dom";
import MuiThemeProvider from "material-ui/styles/MuiThemeProvider";
import lightBaseTheme from "material-ui/styles/baseThemes/lightBaseTheme";
import getMuiTheme from "material-ui/styles/getMuiTheme";
import injectTapEventPlugin from "react-tap-event-plugin";

// Components
import Navbar from "./components/Navbar";
import HomePage from "./components/HomePage";
import SpotMap from "./components/SpotMap";
import SignUpPage from "./components/containers/SignUpPage";
import LoginPage from "./components/containers/LoginPage";
import DashboardPage from "./components/containers/DashBoardPage";
import NotFound from "./components/NoteFound";
import Auth from "./modules/Auth";
import "./styles/App.css";

injectTapEventPlugin();

const handleLogout = event => {
  Auth.deauthenticateUser();
  this.props.history.push("/login");
};

const isLoggedIn = event => {
  if (Auth.isUserAuthenticated()) {
    this.props.history.push(DashboardPage);
  } else {
    this.props.history.push(HomePage);
  }
};

class App extends Component {
  render() {
    return (
      <MuiThemeProvider muiTheme={getMuiTheme(lightBaseTheme)}>
        <Router>
          <div>
            <Navbar />
            <Switch>
              <Route exact path="/" component={isLoggedIn} />
              <Route path="/spotmap" component={SpotMap} />
              <Route path="/dashboard" component={DashboardPage} />
              <Route path="/signup" component={SignUpPage} />
              <Route path="/login" component={LoginPage} />
              <Route path="/logout" component={handleLogout} />
              <Route component={NotFound} />
            </Switch>
          </div>
        </Router>
      </MuiThemeProvider>
    );
  }
}

export default App;

This is written in React Router v3 and this is what I need to convert to React Router V4.这是用 React Router v3 编写的,这是我需要转换为 React Router V4 的内容。 The routes that does not work for me are the "/" and "logout" routes.对我不起作用的路线是“/”和“注销”路线。

import Base from './components/Base.jsx';
import HomePage from './components/HomePage.jsx';
import DashboardPage from './containers/DashboardPage.jsx';
import LoginPage from './containers/LoginPage.jsx';
import SignUpPage from './containers/SignUpPage.jsx';
import Auth from './modules/Auth';


const routes = {
  // base component (wrapper for the whole application).
  component: Base,
  childRoutes: [

    {
      path: '/',
      getComponent: (location, callback) => {
        if (Auth.isUserAuthenticated()) {
          callback(null, DashboardPage);
        } else {
          callback(null, HomePage);
        }
      }
    },

    {
      path: '/login',
      component: LoginPage
    },

    {
      path: '/signup',
      component: SignUpPage
    },

    {
      path: '/logout',
      onEnter: (nextState, replace) => {
        Auth.deauthenticateUser();

        // change the current URL to /
        replace('/');
      }
    }

  ]
};

export default routes;

For the / route you should use render like this:对于/路线,您应该像这样使用渲染

<Route exact path="/" render={() => {
  if (Auth.isUserAuthenticated()) { 
    (<DashboardPage)/>)
  } else {
    (<HomePage/>)
  }
}} />

For your /logout route using <Redirect>对于使用<Redirect> /logout路由

<Route path="/logout" render={() => {
    Auth.deauthenticateUser();
    return <Redirect to={{ pathname: "/login" }} />;
    }}
/>

I post a second solution for the /logout path using withRouter and this.props.history.push('/login') .我使用withRouterthis.props.history.push('/login')为 /logout 路径发布了第二个解决方案。

  1. Point the /logout Route to its own component "Logout"将 /logout 路由指向它自己的组件“Logout”
  2. wrap the Logout component with withRouter method from react-router-dom.使用 react-router-dom 中的 withRouter 方法包​​装 Logout 组件。

Logout.js登出.js

import React, { Component } from "react";
import Auth from "../modules/Auth";
import { withRouter } from "react-router-dom";

class Logout extends Component {
  constructor(props) {
    super(props);
    this.handleLogout = this.handleLogout.bind(this);
  }
  handleLogout() {
    Auth.deauthenticateUser();
    this.props.history.push("/login");
  }
  render() {
    return (
      <div>
        {this.handleLogout()}
      </div>
    );
  }
}
export default withRouter(Logout);

I would use useHistory.我会使用 useHistory。

Do:做:

import { useHistory } from 'react-router-dom';

Instead of:代替:

import { useHistory } from 'react-router';

(Or else the same error message will appear.) (否则会出现相同的错误消息。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM