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

标签 reactjs api axios

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

相关文章:

java - 如何在Eclipse项目中正确集成OpenNLP API?

ruby-on-rails - 我如何在 curb 中指定 SSL 版本

javascript - 使用 window.axios 时 moxios 无法正常工作

javascript - 使用 flexbox 垂直对齐内容

javascript - 在 Javascript 中使用带有数字的 charAt

javascript - axios createError.js :16 Uncaught (in promise) Error: Request failed with status code 400

api - 如何将错误异常存储在变量中并作为json返回

laravel - Web 开发堆栈 - 疯狂 --- 最佳实践架构和部署?

vue.js - Vue Axios 动态 URL

javascript - ReactJS:链接动态转到下一页