首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将条件重定向到react中的URL

将条件重定向到react中的URL
EN

Stack Overflow用户
提问于 2021-05-27 08:54:58
回答 1查看 1.1K关注 0票数 1

我正在构建一个“忘记密码”页面。以下是我的代码流程:

在单击“忘记密码”时打开带有url /auth/new-password.

  • Here,的
  1. 将输入作为电子邮件并将其发送到已注册的电子邮件(如果它存在于DB中)。
  2. 在发送OTP后,将重定向到一个新的URL /auth/forgot-password,其余的详细信息将被输入(例如。OTP,新密码等)

由于这个流,用户可以通过搜索路径/auth/new-password来访问它。但我不想这样。用户只能通过/auth/forgot-password访问此url。如果用户搜索先前的/auth/forgot-password URL,则应将用户重定向到该URL。

目前,在“我的路线”页面中,我正在这样做:

<ContentRoute path="/auth/forgot-password" component={ForgotPassword}/>

<ContentRoute path="/auth/new-password" component={NewPassword} />

由于一些限制,我无法更改现有的代码流。我怎样才能改变这一点来展示上面解释的行为呢?

EN

回答 1

Stack Overflow用户

发布于 2021-05-27 10:12:10

最简单的方法是创建一个HOC (高阶组件)。

当我希望用户在访问某个站点的页面之前进行身份验证时,我总是创建一个名为AuthRoute的临时文件,如下所示。

AuthRoute.js

代码语言:javascript
复制
import { connect } from "react-redux";
import { Redirect, Route } from "react-router-dom";

const AuthRoute = props => {
    const { authUser, location } = props;

    if(!authUser) {
        return <Redirect to={{
            pathname: "/",
            state: { prevLoc: location.pathname }
        }} />
    }

    return <Route {...props} />;
};

function mapStateToProps({ authUser }) {
    return {
        authUser
    }
}

export default connect(mapStateToProps)(AuthRoute);

然后将它包含到像这样的App组件中。

App.js

代码语言:javascript
复制
import { Fragment } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import AuthRoute from './components/AuthRoute'; // AuthRoute Import
import Dashboard from './components/Dashboard';

const App = () => {
  return (
    <Router>
        <Switch>
          {/* Include the AuthRoute component for the relevant page */}
          <AuthRoute path="/home" component={Dashboard} /> 
          <Route path="/" component={Login} />
        </Switch>
    </Router>
  )
}

此实现将检查用户是否在/auth/forgot-password页面上输入他们的电子邮件地址。

具有临时实现的已完成项目- https://github.com/yushanwebdev/reactnd-would-you-rather

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67718863

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档