【发布时间】:2020-02-13 14:31:26
【问题描述】:
我在 React 中有一个组件,在 useEffect 中我进行了两次 API 调用并设置了两种状态。仍然在useEffect 之后,我试图设置另一个状态,其中一个状态由 API 更新。如果我通过保持useEffect 的方括号参数为空来执行此操作,则不会设置状态。如果我传递括号中的状态常量,它会进入无限循环。
async function fetchData() {
const agentRes = await fetch("http://localhost:3004/agentsdata");
agentRes
.json()
.then(res => setAgents(res))
.catch(err => console.log(err));
const queueRes = await fetch("http://localhost:3004/queuedata");
queueRes
.json()
.then(res => setBaseQueues(res))
.catch(err => console.log(err));
}
useEffect(() => {
fetchData();
let pge;
if (props.location.data !== undefined) {
pge = props.location.data.page;
}
else {pge = 1;}
setUser(props.match.params.user);
setPage(pge);
let lowerB = (0 +((pge - 1) * 10));
let upperB = 10 + ((pge - 1) * 10);
setQueues(baseQueues.slice(lowerB, upperB)); // here the state is not getting set.
}, [queues])
我如何做到这一点,以便我可以设置该状态以及我需要在 useEffect 中进行设置。
【问题讨论】:
标签: javascript reactjs react-hooks setstate