[英]How to solve React "too many re-renders" error
我正在学习 React 钩子并有以下代码:
import React, { useState, useEffect } from "react";
import "./App.css";
function App() {
const [count, setCount] = useState(0);
const [person, setPerson] = useState([]);
useEffect(() => {
getPerson();
}, []);
const getPerson = async () => {
const response = await fetch("https://api.randomuser.me");
const data = await response.json();
setPerson(data.results);
};
return (
<div className="App">
<p>You clicked {count} times</p>
<button onClick={() => getPerson(), setCount(count + 1)}>Click Me</button>
<div>{person.map(person => person.name.first)}</div>
</div>
);
}
export default App;
当我单击“单击我”按钮时,我希望计数器更新并进行 API 调用以获取随机人员。 单独地,这两部分代码都可以工作。 但是,当我尝试同时执行这两项操作时,会收到此错误: Too many re-renders. React limits the number of renders to prevent an infinite loop.
Too many re-renders. React limits the number of renders to prevent an infinite loop.
我是 React 的新手,无法弄清楚为什么会这样。 我在 UseEffect 方法中添加了[]
作为第二个参数,我认为这可能会阻止页面不断重新渲染。
任何人都可以帮忙吗? 谢谢!
不确定您是否将代码复制到了您的问题中,但这里有一些可以让它变得更好的东西。
...
return (
<div className="App">
<p>You clicked {count} times</p>
<button onClick={() => { getPerson(); setCount(count + 1)}}>Click Me</button>
<div>{person.map(person => person.name.first)}</div>
</div>
);
这会起作用,但同时也不好,也许您只想在重新请求完成时增加计数?
所以你可以做的是使用.then
onClick={() => { getPerson().then(() => setCount(count + 1))}}
这是不正确的,因为useEffect
只是类似于componentDidMount
和componentDidUpdate
。 如果您在此方法中更新状态而不对其进行限制,则会导致无限渲染。
import React, { useState, useEffect } from "react";
import "./App.css";
function App() {
const [count, setCount] = useState(0);
const [person, setPerson] = useState([]);
useEffect(() => {
// You need to restrict it at some point
// This is just dummy code and should be replaced by actual
if (person.length === 0) {
getPerson();
}
}, []);
const getPerson = async () => {
const response = await fetch("https://api.randomuser.me");
const data = await response.json();
setPerson(data.results);
};
return (
<div className="App">
<p>You clicked {count} times</p>
<button onClick={() => {getPerson(); setCount(count + 1);}}>Click Me</button>
<div>{person.map(person => person.name.first)}</div>
</div>
);
}
export default App;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.