【发布时间】:2020-12-20 15:56:09
【问题描述】:
我正在尝试在 React 组件中进行 2 个 HTTP 调用,然后该组件将为使用 useState 定义的 2 个属性调用 setter。为了防止无限重新渲染,我遵循了我认为正确的方法,但这仍然在发生。这是我的代码:
function Dashboard({ history = [] }) {
const [teamInfo, setTeamInfo] = useState(null);
const [survey, setSurvey] = useState(null);
const [open, setOpen] = useState(false);
const user = getUser();
const getSurveyHandler = async () => {
const surveyResponse = await getSurveys('standard');
setSurvey(surveyResponse.data);
};
const getTeamInfoHandler = async () => {
const teamInfoResponse = await getTeamInfo(user.teamId);
setTeamInfo(teamInfoResponse);
};
useEffect(() => {
document.body.style.backgroundColor = '#f9fafb';
getSurveyHandler();
getTeamInfoHandler();
}, [survey, teamInfo]);
如您所见,我已经在 useEffect 之外定义了函数,并将两个状态变量传递到将检查以防止无限重新渲染的依赖数组中。 谁能明白为什么这仍然发生?
谢谢
【问题讨论】:
-
依赖数组中的状态变量导致此处无限渲染。
标签: reactjs http infinite-loop