Skip to content
开发文档
条件数据请求

条件请求

¥Conditional Fetching

条件式

¥Conditional

使用 null 或传递函数作为 key 有条件地获取数据。如果函数抛出或返回错误值,SWR 将不会启动请求。

¥Use null or pass a function as key to conditionally fetch data. If the function throws or returns a falsy value, SWR will not start the request.

// conditionally fetch
const { data } = useSWR(shouldFetch ? '/api/data' : null, fetcher)
 
// ...or return a falsy value
const { data } = useSWR(() => shouldFetch ? '/api/data' : null, fetcher)
 
// ...or throw an error when user.id is not defined
const { data } = useSWR(() => '/api/data?uid=' + user.id, fetcher)

依赖

¥Dependent

SWR 还允许你获取依赖于其他数据的数据。它确保最大可能的并行性(避免瀑布),以及在下一次数据请求需要一段动态数据时串行获取。

¥SWR also allows you to fetch data that depends on other data. It ensures the maximum possible parallelism (avoiding waterfalls), as well as serial fetching when a piece of dynamic data is required for the next data fetch to happen.

function MyProjects () {
  const { data: user } = useSWR('/api/user')
  const { data: projects } = useSWR(() => '/api/projects?uid=' + user.id)
  // When passing a function, SWR will use the return
  // value as `key`. If the function throws or returns
  // falsy, SWR will know that some dependencies are not
  // ready. In this case `user.id` throws when `user`
  // isn't loaded.
 
  if (!projects) return 'loading...'
  return 'You have ' + projects.length + ' projects'
}