【发布时间】:2020-08-15 05:26:23
【问题描述】:
我正在使用 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 并单击 Fetch 按钮时,它仍将 FirstName 和 LasName 显示为“默认”。
我认为我的onSuccess 回调函数有问题。
这里是codesanbdbox演示:https://codesandbox.io/s/nervous-hill-mn0kz?file=/pages/index.js
【问题讨论】:
标签: javascript reactjs next.js