[英]Function not passing as prop in React app and how to prevent the same function from going into infinite loop
I am setting up private routing in my react app so that only authenticated user can visit home and profile page And if the user is not authenticated, then he can only visit the login and signup page.我在我的反应应用程序中设置私有路由,以便只有经过身份验证的用户才能访问主页和个人资料页面如果用户未通过身份验证,那么他只能访问登录和注册页面。
What I am doing for this is that I am calling the login function which I have created in the privateRoute.js file while the login function is in the Login.js file我为此做的是,我正在调用我在 privateRoute.js 文件中创建的登录 function,而登录 function 在 Login.js 文件中
Now as I know that I can pass the login function from the Login.js file to the privateRoute.js file as a prop.现在我知道我可以将 Login.js 文件中的登录 function 作为道具传递给 privateRoute.js 文件。 Now as soon as when I do this and run the functionality, my login function goes into an infinite loop because one condition of my login function becomes true in Login.js file and it goes running and running.
现在,一旦我执行此操作并运行该功能,我的登录 function 就会进入无限循环,因为我的登录 function 的一个条件在 Login.js 文件中变为 true 并且它继续运行和运行。
So how do I prevent that condition from being true in the Login.js file and then use the login function in the privateRoute.js file?那么如何在 Login.js 文件中防止该条件为真,然后在 privateRoute.js 文件中使用登录 function 呢?
my code is below.我的代码如下。
Login.js登录.js
import React, { useState } from "react";
import { Form, Button } from "react-bootstrap";
import { Link } from "react-router-dom";
import RequireAuth from "./PrivateRoute";
const Login = () => {
const initialValues = {
email: "",
password: "",
};
const [userData, setUserData] = useState(initialValues);
const AuthenticateUser = () => {
const localInfo = JSON.parse(localStorage.getItem("signUpUser"));
if (localInfo === null) {
alert("No user exist");
return false;
} else {
localInfo?.map((item) => {
const userName = item.email;
const userPassword = item.password;
if (userName === userData.email && userPassword === userData.password) {
alert("Login Successfully.");
} else {
alert("Login Failed.");
return false;
}
});
setUserData(initialValues);
}
};
return (
<>
<Form className="loginForm">
<Form.Group className="mb-3" controlId="formBasicEmail">
<Form.Label>Email Address</Form.Label>
<Form.Control
type="email"
placeholder="Enter email"
value={userData.email}
name="email"
onChange={(e) =>
setUserData({ ...userData, [e.target.name]: e.target.value })
}
/>
</Form.Group>
<Form.Group className="mb-3" controlId="formBasicPassword">
<Form.Label>Password</Form.Label>
<Form.Control
type="password"
placeholder="Password"
name="password"
value={userData.password}
onChange={(e) =>
setUserData({ ...userData, [e.target.name]: e.target.value })
}
/>
</Form.Group>
<Form.Group className="mb-3" controlId="formBasicCheckbox"></Form.Group>
<Button
variant="primary"
type="submit"
onClick={() => AuthenticateUser()}
>
Login
</Button>
<div className="txtToSignUpBtn">
<span>OR</span> <Link to="/signUp">Click here to Register</Link>
</div>
</Form>
<RequireAuth AuthenticateUser={AuthenticateUser} />
</>
);
};
export default Login;
PrivateRoute.js PrivateRoute.js
import React from 'react'
import { Navigate } from 'react-router-dom';
const RequireAuth = ({ AuthenticateUser }) => {
let auth = AuthenticateUser;
if (!auth) {
return <Navigate to="/" />,
}
}
export default RequireAuth;
App.js应用程序.js
import React from "react";
import Login from "./Login";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import Header from "./Header";
import RequireAuth from "./PrivateRoute";
const App = () => {
return (
<>
<Router>
<Routes>
<Route
exact
path="/home"
element={
<RequireAuth>
<Header />
</RequireAuth>
}
/>
<Route exact path="/" element={<Login />} />
</Routes>
</Router>
</>
);
};
export default App;
you are rendering the RequireAuth component in your login file, so every time the page loads, it is testing for the authentication and rerouting you to the login page.您正在登录文件中呈现 RequireAuth 组件,因此每次页面加载时,它都会测试身份验证并将您重新路由到登录页面。 remove the RequiredAuth component from the login page.
从登录页面中删除 RequiredAuth 组件。 If you want to access the authenticate user function, I would just put it in a separate file and export it from there to both.
如果要访问经过身份验证的用户 function,我只需将其放在单独的文件中,然后从那里导出到两者。 That being said, I would also recommend using something like recoil or redux to externalize the state values for the login.
话虽如此,我还建议使用诸如 recoil 或 redux 之类的东西来外部化登录的 state 值。 you could use something like a custom hook that stores the login information and then in the app.js file you can just render the homepage if the login is correct, if not render the login page.
您可以使用存储登录信息的自定义钩子之类的东西,然后在 app.js 文件中,如果登录正确,则可以仅呈现主页,如果不呈现登录页面。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.