如何将用户重定向到 url React [英] How to redirect user to url React

查看:62
本文介绍了如何将用户重定向到 url React的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个听起来很简单的问题,但我就是找不到解决方案.我已经针对标准 JS 和专门针对 React 的类似问题尝试了多个答案,但我似乎找不到可行的方法.

I have a question that sounds quite simple but I just can't find a solution. I have tried multiple answers on similar questions for both standard JS and specifically for React, but I can't seem to find something that works.

当我的用户在未登录的情况下导航到网站时,我想将他们重定向到我的登录屏幕.对此的工作声明是什么?提前致谢.

I want to redirect my users to my login screen when they navigate to the website without being logged in. What is a working statement for this? Thanks in advance.

推荐答案

如果你使用像 React Router: Declarative Routing for React 这样的东西.js,这是正确的重定向方式,您可以使用 Redirect API 有两种方式:

If you use something like React Router: Declarative Routing for React.js, which is the right way to do redirects, you can use Redirect API in two ways:

对于使用 ,你需要做的就是,有条件或者在组件内部,使用:

For using <Redirect to="" />, all you need to do is, with a condition or inside the component, use:

<Redirect to="/somewhere/else" />
{/* Or in your case... */}
<Route exact path="/">
  {loggedIn ? <Redirect to="/dashboard" /> : <PublicHomePage />}
</Route>

使用withRouter():

import React from "react";
import { withRouter } from "react-router";

// A simple component that shows the pathname of the current location
class App extends React.Component {

  componentDidMount() {
    // Check user logged in and redirect somewhere.
    if (loggedIn) {
      // Something like this.
      location.replace("/dashboard");
    }
  }

  render() {
    const { match, location, history } = this.props;
    return <div>You are now at {location.pathname}</div>;
  }
}

// Create a new component that is "connected" (to borrow redux
// terminology) to the router.
const App = withRouter(App);

这篇关于如何将用户重定向到 url React的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆