跳至内容
文档
条件数据获取

条件获取

条件

使用 null 或者传递一个函数作为 key 来有条件地获取数据。如果函数抛出异常或返回一个假值,SWR 将不会启动请求。

// 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)

依赖

SWR 还允许您获取依赖于其他数据的數據。它确保了尽可能高的并行性(避免瀑布式请求),以及在进行下一个数据获取时需要动态数据时的串行获取。

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'
}