React应用触发Too many re-renders错误,请求排查原因
问题原因及解决方案
核心问题
无限重渲染的根源在 Auth.js 的按钮点击事件绑定上:你直接调用了 viewLogin(false) 和 viewLogin(true),这会导致组件每次渲染时都执行状态更新函数,触发新一轮渲染,形成无限循环。
修复代码
修改 Auth.js 中的按钮 onClick 绑定,改用箭头函数包裹,确保只有点击按钮时才执行状态更新:
import { useState } from "react"; const Auth = () => { const [isLogin, setIsLogin] = useState(true); const [error, setError] = useState(); const viewLogin = (status) => { setError(null); setIsLogin(status); }; return ( <div className="auth-container"> <div className="auth-container-box"> <form> <h2>{isLogin ? "Please log in" : "Please sign up"}</h2> <input type="email" placeholder="email" /> <input type="password" placeholder="password" /> {!isLogin && <input type="password" placeholder="confirm pass" />} <input type="submit" className="create" /> {error && <p>{error}</p>} </form> <div className="auth-options"> <button onClick={() => viewLogin(false)}> Sign up </button> <button onClick={() => viewLogin(true)}> Login </button> </div> </div> </div> ); }; export default Auth;
原理说明
- 原写法
onClick={viewLogin(false)}会在组件渲染时立即执行viewLogin函数,调用setIsLogin触发状态更新,导致组件重新渲染,重复此过程形成无限循环。 - 改用箭头函数
onClick={() => viewLogin(false)}后,只有当按钮被点击时,才会执行viewLogin函数并更新状态,避免了不必要的重复渲染。
内容的提问来源于stack exchange,提问作者Kevin Nash
相关产品推荐
相关产品推荐

