我正在构建一个“忘记密码”页面。以下是我的代码流程:
在单击“忘记密码”时打开带有url /auth/new-password.
/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} />
由于一些限制,我无法更改现有的代码流。我怎样才能改变这一点来展示上面解释的行为呢?
发布于 2021-05-27 10:12:10
最简单的方法是创建一个HOC (高阶组件)。
当我希望用户在访问某个站点的页面之前进行身份验证时,我总是创建一个名为AuthRoute的临时文件,如下所示。
AuthRoute.js
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
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
https://stackoverflow.com/questions/67718863
复制相似问题