【问题标题】:Fetch error: cannot load resource unless page is refreshed - React获取错误:除非刷新页面,否则无法加载资源 - React
【发布时间】:2021-09-13 01:40:14
【问题描述】:

我创建了一个 fetch 调用:

    fetch(testURL)
      .then(function(response) {
        return response.json();
      })
      .then(function(data) {
        console.log(JSON.stringify("test data", data));
      })
      .catch(() => {
        console.log(Error);
      });

在控制台出现资源无法访问的错误 但是当我刷新时,我可以看到网址。

【问题讨论】:

    标签: reactjs fetch use-effect


    【解决方案1】:

    尝试将 fetch 调用包装在这样的函数中:

      const fetchTest = () => {
        fetch(testURL)
          .then(function(response) {
            return response.json();
          })
          .then(function(data) {
            console.log(JSON.stringify("test data", data));
          })
          .catch(() => {
            console.log(Error);
          });
      };
    

    然后在useEffect中调用函数:

      useEffect(() => {
        fetchTest();
      }, []);
    

    这将确保加载资源而无需先刷新。

    【讨论】:

      猜你喜欢
      • 2017-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-19
      • 1970-01-01
      • 2021-04-28
      • 2012-11-12
      • 2012-05-21
      相关资源
      最近更新 更多