如何使用usewR获得不同API页面的响应?
我正在使用具有不同数据的API URL取决于页面URL,但是我想在一个呼叫中获取所有页面URL,但没有获取任何数据,除非我只尝试获得一个页面。请有人可以帮我吗?
这是我的代码:
function arrayFetcher(urlArr) {
const fetcher = (url) => axios.get(url).then((res) => res.json());
return Promise.all(urlArr.map(fetcher));
}
let urlArray = [];
for(let i = 0; i < 20; i++) {
urlArray.push(`https://api.google.com/page=250&page=${i}&sparkline=false`);
}
const { data } = useSWR(urlArray, arrayFetcher);
{data && console.log(data)}
I am using an API URL that has different data depend on the page URL, but I want to get all the pages URLs in one call, but not getting any data, except when I try to get only one page. Please can someone please help me out?
Here is my code:
function arrayFetcher(urlArr) {
const fetcher = (url) => axios.get(url).then((res) => res.json());
return Promise.all(urlArr.map(fetcher));
}
let urlArray = [];
for(let i = 0; i < 20; i++) {
urlArray.push(`https://api.google.com/page=250&page=${i}&sparkline=false`);
}
const { data } = useSWR(urlArray, arrayFetcher);
{data && console.log(data)}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将数组作为键参数传递到
使用
时,数组中的每个项目将是arrayfetcher
函数中的参数。这意味着,当您尝试访问urlarr
内部arrayfetcher
时,您只访问urlarray
的第一个URL,而不是完整的URL数组本身。一种可能的解决方案是传递对象作为
的关键参数使用
,其中包含urlarray
。When passing an array as the key parameter to
useSWR
, each item in the array will be its own argument in thearrayFetcher
function. This means that when you're trying to accessurlArr
insidearrayFetcher
you're only accessing the first URL of theurlArray
, and not the full array itself.A possible solution is to pass an object as the key parameter in
useSWR
, which containsurlArray
.