React useEffect钩子抛出Uncaught TypeError且组件无法重渲染的问题
编辑说明:添加注释以提升可读性
注意:这是我的第一个React.js应用,我从未成功实现过useState()或useEffect()钩子!
问题描述
我已将一个JS对象从子组件(LoginInputForm.js)传递到父组件(Login.js),这部分运行顺畅。不使用useEffect()时,我的整个API调用完全正常,但无法执行预期的条件逻辑:仅在从子组件获取数据后才执行该API调用并将结果更新到全局上下文,在此之前延迟处理(功能正常后会添加加载状态展示)。我这么做是为了在这个演示项目中模拟登录认证系统,仅当从自定义RESTful API获取到用户ID时才完成登录(经多次测试,API本身运行完美)。我能看到自己构建的登录界面,但尝试用数据库中用户的信息登录时,前端基本停止渲染组件(或无限渲染?),控制台输出报错信息。
错误类型
React抛出Uncaught TypeError,该错误与useEffect()中的两个变量"username"和"password"相关。即使添加了if判断,仍始终提示需要处理这两个变量。
已尝试方案
我尝试过不在useEffect()中设置依赖项(导致无限循环),尝试添加React建议的所有依赖项(问题更严重),按照Udemy课程建议移除状态依赖项,最终尝试将函数作为依赖项(据了解这是不良实践),但仍无法正常工作。
代码展示
import LoginLogo from "../components/login_components/LoginLogo"; import LoginHeader from "../components/login_components/LoginHeader"; import LoginInputForm from "../components/login_components/LoginInputForm"; import UserInputCard from "../components/ui/UserInputCard"; import React from "react"; import { useContext, useEffect, useState } from "react"; import { useNavigate } from "react-router-dom"; import CurrentUserContext from "../storage/current-user-context"; function LoginPage() { const [isLoggingIn, setIsLoggingIn] = useState(false); const navigate = useNavigate(); const currentUserContext = useContext(CurrentUserContext); let loginData; // This is where I get my loginData object function getLoginData(userLoginData) { loginData = userLoginData; setIsLoggingIn(true); } // What I'm currently struggling with useEffect(() => { if (isLoggingIn) { let username = loginData.username; let password = loginData.password; let userId; if ( username != null && username !== undefined && password != null && password !== undefined ) { try { userId = fetch( `https://<my-domain>/api/users/${username}-${password}` ).then((response) => { console.log("HTTP Status Code: ", response.status); if (!response.ok) { console.log(response); throw new Error(`Error! Current Status: ${response.status}`); } else if (response.ok) { return response.json(); } }); } catch (err) { console.log(err); } currentUserContext.getCurrentUser(userId); console.log(userId); } setIsLoggingIn(false); } }, [currentUserContext, loginData, getLoginData]); return ( <div> <UserInputCard> <LoginLogo /> <LoginHeader /> <LoginInputForm onGetLoginData={getLoginData} /> </UserInputCard> </div> ); } export default LoginPage;
请各位Stack Overflow的大神帮帮我!
内容的提问来源于stack exchange,提问作者Chůnky
相关产品推荐
相关产品推荐

