gpt4 book ai didi

javascript - 使用 fetch 更新状态然后在 useEffect 中使用状态不起作用

转载 作者:行者123 更新时间:2023-12-01 00:08:34 25 4
gpt4 key购买 nike

我在 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 中执行的操作。

最佳答案

useEffect(() => {
const doAsyncStuff = async () => {
await fetchData(); // wait for this data to load
const { data } = props.location;
let pge = data !== undefined ? data.page : 1;
setUser(props.match.params.user);
setPage(pge);

let lowerB = (0 +((pge - 1) * 10));
let upperB = 10 + ((pge - 1) * 10);

setQueues(state => state.slice(lowerB, upperB)); // change here
}
doAsyncStuff();
}, [queues])

首先我认为你需要等待数据加载,所以你必须等待 await fetchData();

然后在设置setQueues时,您必须执行setQueues(state => state.slice(lowerB, upperB));

关于javascript - 使用 fetch 更新状态然后在 useEffect 中使用状态不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60210190/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com