javascript - 无法捕获 onSuccess 回调中 API 调用返回的数据

标签 javascript reactjs next.js

我正在使用SWR react hook from nextJS使用 onSuccess 回调函数,但它没有按我的预期工作。 onsuccess 回调已被调用,但未接收任何数据。

这是显示问题的最小代码:

pages/index.js

import useSWR from "swr";

export default function index() {
  let data = { FirstName: "Default", LastName: "Default" },
    error;
  const fetcher = url =>
    fetch(url).then(r => {
      r.json();
    });
  const [shouldFetch, setShouldFetch] = React.useState(false);
  useSWR(shouldFetch ? "/api/data" : null, fetcher, {
    onSuccess: (data, key, config) => {
      console.log({ data }); //this always prints "undefined"
      this.data = data;
      this.error = error;
    }
  });

  function handleClick() {
    setShouldFetch(true);
  }
  return (
    <>
      <button onClick={e => handleClick()}>Fetch</button>
      Data retrieved from server is: {JSON.stringify(data)}
      Error received from server is: {JSON.stringify(error)}
    </>
  );
}

pages/api/data.js:

export default (req, res) => {
  res.statusCode = 200;
  res.setHeader("Content-Type", "application/json");
  res.send({ FirstName: "John", LastName: "Doe" });
};

当我转到 localhost:3000/index 并单击“获取”按钮时,它仍然将 FirstName 和 LasName 显示为“默认”。

我认为我的 onSuccess 回调函数有问题。

这里是codesanbdbox演示:https://codesandbox.io/s/nervous-hill-mn0kz?file=/pages/index.js

最佳答案

您需要做的是从fetcher函数返回数据

const fetcher = url =>
   fetch(url).then(r => {
   return r.json();
});

此外,我建议按照最佳实践重构代码。理想情况下,您应该将以下内容包装在函数内。

useSWR(shouldFetch ? "/api/data" : null, fetcher, {
   onSuccess: (data, key, config) => {
      console.log({ data }); //this always prints "undefined"
      this.data = data;
      this.error = error;
   }
});

以防止每次 react 渲染时都运行它。我还建议将数据移至 React 状态,而不是让 shouldFetch 处于状态。

关于javascript - 无法捕获 onSuccess 回调中 API 调用返回的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61530348/

相关文章:

javascript - 无法更改表格单元格的高度

reactjs - 如何将 React-Router 与模型结合使用

node.js - 检查React应用程序是否正在Docker容器中运行

javascript - 在react js中显示json中的键和值对

javascript - 不使用 anchor 链接转到选项卡?

php - ckeditor 值等于下拉列表的结果

javascript - 我如何根据另一个 div jQuery 中的内容显示一个 div

android - 如何仅向中间件授予 webview 应用程序的访问权限 - next.js

github - Vercel 通过 Github 构建失败,但可以通过 Vercel --prod 进行构建

reactjs - 如何在 React 中将 HEIC 转换为 JPG?