参数
¥Arguments
默认情况下,key
将作为参数传递给 fetcher
。所以下面的 3 个表达式是等价的:
¥By default, key
will be passed to fetcher
as the argument. So the following 3 expressions are equivalent:
useSWR('/api/user', () => fetcher('/api/user'))
useSWR('/api/user', url => fetcher(url))
useSWR('/api/user', fetcher)
多个参数
¥Multiple Arguments
在某些情况下,将多个参数(可以是任何值或对象)传递给 fetcher
函数很有用。例如授权的获取请求:
¥In some scenarios, it's useful to pass multiple arguments (can be any value or object) to the fetcher
function.
For example an authorized fetch request:
useSWR('/api/user', url => fetchWithToken(url, token))
这是不正确的。因为数据的标识符(也是缓存键)是 '/api/user'
,所以即使 token
发生变化,SWR 仍然会使用相同的键并返回错误的数据。
¥This is incorrect. Because the identifier (also the cache key) of the data is '/api/user'
,
even if token
changes, SWR will still use the same key and return the wrong data.
相反,你可以使用数组作为 key
参数,其中包含 fetcher
的多个参数:
¥Instead, you can use an array as the key
parameter, which contains multiple arguments of fetcher
:
const { data: user } = useSWR(['/api/user', token], ([url, token]) => fetchWithToken(url, token))
fetcher
函数按原样接受 key
参数,并且缓存键也将与整个 key
参数关联。在上面的示例中,url
和 token
都与缓存键绑定。
¥The fetcher
function accepts the key
parameter as is, and the cache key will also be associated with the entire key
argument. In the above example, url
and token
are both tied to the cache key.
在之前的版本(< 2.0.0)中,当 key
参数为数组类型时,fetcher
函数将从原始 key
接收扩展参数。例如,键 [url, token]
将成为 fetcher
函数的 2 个参数 (url, token)
。
¥In the previous versions (< 2.0.0), The fetcher
function will receive the spreaded arguments from original key
when the key
argument is array type. E.g., key [url, token]
will become 2 arguments (url, token)
for fetcher
function.
传递对象
¥Passing Objects
从 SWR 1.1.0 开始,类似对象的键将在后台自动序列化。
¥Since SWR 1.1.0, object-like keys will be serialized under the hood automatically.
假设你有另一个函数可以在用户范围内获取数据:fetchWithUser(api, user)
。你可以执行以下操作:
¥Say you have another function that fetches data with a user scope: fetchWithUser(api, user)
. You can do the following:
const { data: user } = useSWR(['/api/user', token], fetchWithToken)
// ...and then pass it as an argument to another useSWR hook
const { data: orders } = useSWR(user ? ['/api/orders', user] : null, fetchWithUser)
你可以直接传递一个对象作为键,fetcher
也会收到该对象:
¥You can directly pass an object as the key, and fetcher
will receive that object too:
const { data: orders } = useSWR({ url: '/api/orders', args: user }, fetcher)
在旧版本(< 1.1.0)中,SWR 会浅层比较每个渲染上的参数,并在其中任何一个发生更改时触发重新验证。
¥In older versions (< 1.1.0), SWR shallowly compares the arguments on every render, and triggers revalidation if any of them has changed.