简体   繁体   English

Function 没有在 React 应用程序中作为道具传递以及如何防止相同的 function 进入无限循环

[英]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.

相关问题 传递循环作为prop反应时的无限循环 - infinate loop while passing function as prop react 反应传递 function 作为道具 - React passing function as prop 在React中传递函数作为道具 - Passing a function as a prop in React React Native-使用prop的传递函数-作为prop - React Native - passing function that uses a prop, - as a prop 我如何在React中不通过HOC(高阶组件)访问方法/函数? - How would I access a method/function from a HOC (Higher Order Component) in React without passing it as a prop? 将 function 作为道具传递给 Typescript 反应功能组件 - Passing a function as a prop to a Typescript React Functional Component React Hooks:传递 state 道具不是 function? - React Hooks: Passing state prop is NOT a function? 如何在 useEffect 中包含缺少的依赖项但防止 function 的无限循环执行? - How to include missing dependency in useEffect but prevent infinite loop execution of function? 在将 function 传递给子组件时,React 似乎只允许事件侦听器道具名称与 function 名称相同 - React seems to only allow the event listener prop name to be same as the function name when passing that function to the child component 为什么传递道具无限循环会使我的应用程序崩溃,甚至不更新道具? - Why does passing a prop infinite loop crash my app and doesn't even update the prop?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM