Skip to content
开发文档
数据请求

数据请求

¥Data Fetching

const { data, error } = useSWR(key, fetcher)

这是 SWR 非常基本的 API。这里的 fetcher 是一个异步函数,它接受 SWR 的 key,并返回数据。

¥This is the very fundamental API of SWR. The fetcher here is an async function that accepts the key of SWR, and returns the data.

返回值将作为 data 传递,如果抛出,它将作为 error 被捕获。

¥The returned value will be passed as data, and if it throws, it will be caught as error.

💡

注意,如果是 provided globally,则参数中的 fetcher 可以省略。

¥Note that fetcher can be omitted from the parameters if it's provided globally.

Fetch

你可以使用任何库来处理数据请求,例如 fetch polyfill developit/unfetch (opens in a new tab)

¥You can use any library to handle data fetching, for example a fetch polyfill developit/unfetch (opens in a new tab):

import fetch from 'unfetch'
 
const fetcher = url => fetch(url).then(r => r.json())
 
function App () {
  const { data, error } = useSWR('/api/data', fetcher)
  // ...
}
💡

如果你使用的是 Next.js,则不需要导入这个 polyfill:
New Built-In Polyfills: fetch(), URL, and Object.assign

¥If you are using Next.js, you don't need to import this polyfill:
New Built-In Polyfills: fetch(), URL, and Object.assign

Axios

import axios from 'axios'
 
const fetcher = url => axios.get(url).then(res => res.data)
 
function App () {
  const { data, error } = useSWR('/api/data', fetcher)
  // ...
}

GraphQL

或者将 GraphQL 与 graphql-request (opens in a new tab) 等库一起使用:

¥Or using GraphQL with libs like graphql-request (opens in a new tab):

import { request } from 'graphql-request'
 
const fetcher = query => request('/api/graphql', query)
 
function App () {
  const { data, error } = useSWR(
    `{
      Movie(title: "Inception") {
        releaseDate
        actors {
          name
        }
      }
    }`,
    fetcher
  )
  // ...
}

如果你想将变量传递给 GraphQL 查询,请查看 多个参数

¥If you want to pass variables to a GraphQL query, check out Multiple Arguments.