react错误:Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infini

react错误:

Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.

react错误:Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infini_第1张图片

原因1:

错误写法:

<div className='article_item' onClick={toArticleDetail}>testdiv>

正确写法:

//注: 函数必须是调用函数,而不是只写函数名,即里面要写为:toArticleDetail() 【函数名后面必须带上括号】
{toArticleDetail()}}>testdiv>

原因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,react.js,javascript,前端)