gpt4 book ai didi

reactjs - React Hook useEffect : fetch data using axios with async await . api 调用连续相同的 api

转载 作者:行者123 更新时间:2023-12-04 12:10:49 25 4
gpt4 key购买 nike

当我从 API 获取数据时并使用 useEffect 将响应设置为数组
它叫 API重复连续。

let [product, setproduct] = useState([]);

async function fetchData() {
let response = await axios(
`api`
);
let user = await response.data;
setproduct(user);
console.log(product);
}

useEffect(() => {
fetchData();
});

最佳答案

来自 docs ,

Does useEffect run after every render? Yes! By default, it runs both after the first render and after every update. (We will later talk about how to customize this.) Instead of thinking in terms of “mounting” and “updating”, you might find it easier to think that effects happen “after render”. React guarantees the DOM has been updated by the time it runs the effects.



您可以提供空的依赖数组/ []作为 useEffect 的第二个参数, 同 componentDidMount它将在组件生命周期中只执行一次。
useEffect(() => {
fetchData();
}, []); //This will run only once

关于reactjs - React Hook useEffect : fetch data using axios with async await . api 调用连续相同的 api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57766593/

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