当我从 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/