【问题标题】:How to redirect user to url React [closed]如何将用户重定向到 url React [关闭]
【发布时间】:2021-02-28 12:46:52
【问题描述】:

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

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

【问题讨论】:

标签: javascript reactjs redirect


【解决方案1】:

如果您使用React Router: Declarative Routing for React.js 之类的东西,这是进行重定向的正确方法,您可以通过两种方式使用Redirect API:

  • 使用<Redirect to="" />
  • 使用高阶函数withRouter()

要使用<Redirect to="" />,您只需在条件或组件内部使用:

<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);

【讨论】:

  • location.push 不是重定向,它应该是location.replace。另外,render 生命周期函数是一个纯函数,所以不应该有命令式导航的副作用,这应该在 componentDidUpdate 生命周期方法中完成。
  • @DrewReese 我会更新的。谢谢。我一直在我的应用程序中使用这一切。我也应该在我的客户端应用程序中更新吗?这里可能发生什么坏事?
  • @DrewReese 更新如你所说,使用componentDidMount生命周期方法
【解决方案2】:

您的应用程序的每条路由都必须包装在一个 HOC 中,该 HOC 将检查用户是否在 componentDidMount 中进行了身份验证。 如果未通过身份验证,您将重定向到登录屏幕。

如果您的应用支持令牌进行身份验证: 在 HOC 的componentDidMount 中,您可以检查缓存在某些浏览器存储中的令牌是否仍然有效,并根据有效性决定重定向到登录屏幕

我更喜欢什么

我发现,使用 Redirectreact-router-dom 更具声明性。在这里查看用法:https://reactrouter.com/web/api/Redirect

【讨论】:

  • 问题不在于检查用户是否经过身份验证,这很有效。我似乎找不到重定向的工作声明
  • 哦,明白了!那么,@Praveen 的答案就是你所需要的
  • 不同的库提供不同的重定向API
  • 如果使用 react-router-dom,那么使用&lt;Redirect /&gt; 就是你的答案
【解决方案3】:

只需添加此代码 window.location.replace('new url') 每当执行此行时,窗口将被替换为新定义的 URL! :D

【讨论】:

  • 这应该是 React SPA,而不是普通的 HTML 和 JavaScript。
【解决方案4】:
import { useAuthState } from 'react-firebase-hooks/auth';

firebase.initializeApp({
  //your key from firebase
})

const [user] = useAuthState(auth); 

<section>
      {user ? <ChatRoom /> : <SignIn />}
</section> 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-10
    相关资源
    最近更新 更多