简体   繁体   English

从 React class 组件重定向到另一个页面(路由)

[英]Redirecting to another page(route) from a React class component

I need some help to solve the following issue with using React .我需要一些帮助来解决以下使用React的问题。

In some web app I have a landing page, where I want to redirect the user to the login page in case she or he is not logged in.在某些 web 应用程序中,我有一个登录页面,我想将用户重定向到登录页面以防她或他未登录。

I want to use the following landing page (taken from some tutorial I found on the net) in order to use it as a model for mine.我想使用以下登录页面(取自我在网上找到的一些教程),以便将其用作我的 model。

The problem is that this is a function component while my landing page is a class component .问题是这是一个function 组件,而我的登录页面是一个class 组件 According to what I understand I guess I need to consider the code inside useEffect and (somewhat) transfer it to componentDidMount() in my class component .根据我的理解,我想我需要考虑useEffect中的代码并(在某种程度上)将其转移到我的class 组件中的componentDidMount() But I don't know how to do that.但我不知道该怎么做。 history.replace will not work in a class component (no Hooks in Classes). history.replaceclass 组件中不起作用(类中没有 Hooks)。 Any advice from a more React experienced user will be very welcome.非常欢迎来自更有React经验的用户的任何建议。

import React, { useEffect, useState } from "react";
import { useAuthState } from "react-firebase-hooks/auth";
import { useHistory } from "react-router";
import "./Dashboard.css";
import { auth, db, logout } from "./firebase";

....

function Dashboard() {
  const [user, loading, error] = useAuthState(auth);
  const [name, setName] = useState("");
  const history = useHistory();

  ....

  useEffect(() => { // Important part for my question !
    if (loading) return;
    if (!user) return history.replace("/");
    ....
  }, [user, loading]);

  return (
    <div>
      {/*...*/}
      <button className="dashboard__btn" onClick={logout}>
        Logout
      </button>
    </div>
  );
}

export default Dashboard;

Here is what I tried on my Class Component:这是我在 Class 组件上尝试的内容:

class MyCompo extends React.Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    console.log("--componentDidMount(MyCompo)--");
    const { history } = this.props
    history.push("/login");
  }
  .....
}

But I get the following error:但我收到以下错误:

TypeError: history is undefined
componentDidMount

Following the example on the React Router docs you can use withRouter if your component isn't already receiving the route props, otherwise you can access history from the props.按照React Router 文档中的示例,如果您的组件尚未接收路由道具,您可以使用withRouter ,否则您可以从道具访问history

class MyComponent extends React.Component {
  ...

  componentDidMount() {
    const { history } = this.props
    // do whatever with history here
  }

  ...
}

In react-router-dom version 5 there are a couple ways a class component can access the history object.react-router-dom版本 5 中,class 组件可以通过多种方式访问history object。

  1. Rendered directly by a Route component via the component , or render or children function props so route props ( ie history , location , and match ) are passed.Route组件通过component直接渲染,或者renderchildren function 道具,因此路由道具historylocationmatch )被传递。

    • component : <Route path="....." component={MyCompo} /> component<Route path="....." component={MyCompo} />
    • render : <Route path="....." render={routeProps => <MyCompo {...routeProps} />} /> render<Route path="....." render={routeProps => <MyCompo {...routeProps} />} />

    Access the history object from the passed route props:从传递的路由道具访问history object:

     class MyCompo extends React.Component { componentDidMount() { const { history } = this.props; history.push("/login"); }... }
  2. Decorated by the withRouter Higher Order Component so the route props are injected.withRouter高阶组件装饰,以便注入路由道具。

     import { withRouter } from 'react-router-dom'; class MyCompo extends React.Component { componentDidMount() { const { history } = this.props; history.push("/login"); }... } export default withRouter(MyCompo);

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

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