我正在使用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/