学习React Hooks,我正在开发一个测试应用程序。我的应用程序从API加载数据,然后填充网格。一块蛋糕。当我尝试显示加载指示器时,出现问题。它进入重新渲染循环。这是我所做的:
import React, { useState, useEffect } from 'react';
function MyComp(props) {
const [loading, setLoading] = useState(false);
const [info, setInfo] = useState(null);
useEffect(() => {
setLoading(!loading);
const getData = response => {
if (response.response) {
setInfo(response.response);
} else {
console.log('there was an error');
}
setLoading(!loading);
};
fetch(URL, {})
.then(resp => ({ getData({response: resp}))
.catch(error => ({ getData({ error });
}, []);
return (
<>
{loading ? "Loading" : "Not Loading"}
</>
);
}
export default MyComp;
我在这里想念什么?
答案 0 :(得分:0)
您正在useEffect挂钩中设置加载。更改状态会导致应用程序重新呈现,这也是您在useEffect中无限执行的操作。 因此,一旦应用加载,useEffect挂钩就会运行并更改加载,这再次导致应用重新渲染,并且循环继续进行。
import React, { useState, useEffect } from 'react';
function MyComp(props) {
const [loading, setLoading] = useState(false);
const [info, setInfo] = useState(null);
useEffect(() => {
setLoading(loading => !loading);
const getData = response => {
if (response) {
setInfo(response);
} else {
console.log('there was an error');
}
setLoading(loading => !loading);
};
fetch(URL, {})
.then(resp => getData( resp))
.catch(error => getData(error));
}, []);
return (
<>
{loading ? "Loading" : "Not Loading"}
</>
);
}
export default MyComp;
答案 1 :(得分:0)
经过一些“尝试和错误”(我不得不承认)之后,我找到了以下解决方案:
import React, { useState, useEffect } from 'react';
function MyComp(props) {
const [loading, setLoading] = useState(false);
const [info, setInfo] = useState(null);
useEffect(() => {
setLoading(false);
}, [info]);
function getData(response) {
if (response.response) {
setInfo(response.response);
} else {
console.log('there was an error');
}
}
useEffect(() => {
setLoading(true);
fetch(URL, {})
.then(resp => ({ getData({response: resp}))
.catch(error => ({ getData({ error });
}, []);
return (
<>
{loading ? "Loading" : "Not Loading"}
</>
);
}
export default MyComp;
也许不是最好或最漂亮的方式...但是它对我有用。