我尝试显示数据,并使用带有反应的 swr 数据获取,这是代码:
import useSWR from "swr";
import axios from "axios";
const fetcherFunc = (...args) => {
return axios(...args).then((res) => console.log(res.data));
};
function MyComponent() {
const { data, error } = useSWR(
"https://jsonplaceholder.typicode.com/posts/",
fetcherFunc
);
if (error) return <div>failed to load</div>;
if (!data) return <div>loading...</div>;
return <div>{JSON.stringify(data)}</div>;
}
export default MyComponent;
问题是它在加载时卡住了,数据不会更新,并且未定义,fetcher 中数据的控制台日志似乎也可以工作。
如何在 react 中使用 swr 获取数据并显示获取的数据?
答案 0 :(得分:2)
您应该从 res.data
返回 fetcherFunc
而不是 console.log
-ing 数据。
此外,只需使用 url
作为 fetcherFunc
的参数名称并将该网址传递给 axios.get
(不要在网址上使用 ...url
扩展运算符) .查看How To Use Axios for Data Fetching(传递网址、方法、有效负载等)。
获取数据的函数应如下所示:
const fetcherFunc = (url) => axios.get(url).then((res) => res.data);
至于 useSWR
钩子,像这样使用它:
const { data, error } = useSWR("https://jsonplaceholder.typicode.com/posts/", fetcherFunc);