如何使用 useSWR 获得针对不同 API 页面的一个响应?

How can I get one response for different API pages with useSWR?

我使用的 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)}

将数组作为关键参数传递给 useSWR 时,数组中的每一项都将成为 arrayFetcher 函数中它自己的参数。这意味着当您尝试访问 arrayFetcher 内的 urlArr 时,您只是访问 urlArray 的第一个 URL,而不是整个数组本身。

一个可能的解决方案是pass an object作为useSWR中的关键参数,其中包含urlArray.

const fetcher = (url) => {
    return axios.get(url).then((res) => res.json());
};

const arrayFetcher = ({ urlArray }) => {
    // Get `urlArray` from object param
    return Promise.all(urlArray.map(fetcher));
};

const Component = () => {
    let urlArray = [];
    for(let i = 0; i < 20; i++) {
        urlArray.push(`https://api.google.com/page=250&page=${i}&sparkline=false`);
    }

    // Pass `urlArray` inside object as the key
    const { data } = useSWR({ urlArray }, arrayFetcher); 
    console.log(data);

    // Rest of the component
};