react错误:
Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.
信铁寒胜:
更改页面数据时未放到useEffect方法内,导致页面一直在刷新。
原因1:
错误写法:
<div className='article_item' onClick={toArticleDetail}>test</div>
正确写法:
//注: 函数必须是调用函数,而不是只写函数名,即里面要写为:toArticleDetail() 【函数名后面必须带上括号】 <div className='article_item' onClick={()=>{toArticleDetail()}}>test</div>
原因2:
更改页面数据时未放到useEffect方法内,导致页面一直在刷新。
错误写法:
import React, { Suspense, useState, useEffect } from "react"; import { connect, useSelector } from "react-redux"; function App() { let userMessage = useSelector((state: any) => state.userMessage); let [isLogin, setIsLogin] = useState(false); if (userMessage.userName && userMessage.userId) { setIsLogin(true); // 该处数据更新造成页面不断刷新 } return ( <div>{isLogin}</div> ); }
正确写法:
import React, { Suspense, useState, useEffect } from "react"; import { connect, useSelector } from "react-redux"; function App() { let userMessage = useSelector((state: any) => state.userMessage); let [isLogin, setIsLogin] = useState(false); //使用useEffect(()=>{},[]) //页面只更新一次 useEffect(() => { if (userMessage.userName && userMessage.userId) { setIsLogin(true); } }, []); return ( <div>{isLogin}</div> ); }
参考:
标签:react,userMessage,limits,React,renders,useEffect,页面 From: https://www.cnblogs.com/wwssgg/p/18036424