React js重定向不会重定向到新的URL

问题描述 投票:1回答:2

我是React js的新手,并开始在我的一个项目中进行实践。

用户登录后我想要什么,然后应将其重定向到另一条将呈现另一组件的路由。

为了重定向,我正在使用Redirect中的react-router-dom组件,但它似乎对我不起作用。如果我使用props.history.push(),则可以使用。

我想澄清

  • Redirect在什么情况下有效?
  • 我应该何时使用Redirect,何时使用props.history.push()

这是我的密码箱演示。

https://codesandbox.io/embed/react-protected-routes-n587m?fontsize=14&hidenavigation=1&theme=dark

reactjs react-router
2个回答
0
投票

[Redirect组件需要呈现为有效,并且事件处理程序返回的值不呈现或通常不使用]

如果您希望重定向或更改事件处理程序内部的路由,则需要使用history.push

export const LandingPage = props => {
  return (
    <div>
      <h1>Landing Page</h1>
      <button
        onClick={() => {
          auth.login(() => {
             props.history.push("/app")
          });
        }}
      >
        Login
      </button>
    </div>
  );
};

可以在更新状态时使用重定向,并且根据状态的存在,您可以像这样呈现重定向组件

return loggedIn && <Redirect to="/app" />

0
投票

欢迎使用js !,看来您正在尝试加载Redirect,就好像它是一个函数,但它不是一个函数!它是React Component!有关反应成分的更多信息:react documentationww3Schools

重定向在您想更改网站方向时(尝试这样做时)有效,但是您必须将其用作组件。

当您在组件的一个子组件中使用历史记录时,应使用props.history.push(),但两者的工作原理相似,因为有些人会做类似的事情,因此您很难定义何时使用它,因为它们不在乎,但是如果您想了解更多信息,请查看此帖子StackOverflow: In React is it always better to render a Redirect than use this.props.history.push?

关于您的代码,请注意您在react中使用的版本,因为在React 16.8中有一个功能可以使用react挂钩并将功能组件用作react组件非常有趣,在您的情况下,您不能通过不使用React.memo来控制元素的状态,但是我更喜欢使用React components,在这种情况下,您可以使用类似这样的内容:

您的登录页面.js

import auth from "./auth";
import { Redirect } from "react-router-dom";

export class LandingPage extends Component {
    constructor(props){
      super(props);
      this.state = {
        authenticated: false
      };
    }

    render(){

    return (
      <div>
        {this.state.authenticated ? (<Redirect to="/app" />) : null}
        <h1>Landing Page</h1>
        <button
          onClick={() => {
            return this.setState({ authenticated: auth.login()})
          }}
        >
          Login
        </button>
      </div>
      );
    }
}

您的auth.js

class Auth {
  constructor() {
    this.authenticated = false;
  }

  login() {
    return this.authenticated = true;
  }

  logout() {
    return this.authenticated = false;
  }

  isAuthenticated() {
    return this.authenticated;
  }
}

export default new Auth();

© www.soinside.com 2019 - 2024. All rights reserved.