如何在 SWR 挂钩中使用查询参数进行变异?

Ann*_*nna 9 reactjs swr

目前我正在使用 SWR 来获取数据,我尝试使用SWR 的Mutation功能来重新获取新数据,但是当我通过添加新查询参数的调用 mutate() 时,出现了问题。

这是我的代码不起作用:

import useSWR, { useSWRConfig } from 'swr'

function Profile () {
  const { mutate } = useSWRConfig()
  const { data } = useSWR('/api/post', fetcher)

  return (
    <div>

      <h1>Title post {data.title}.</h1>

      <button onClick={() => {            
        mutate('/api/post?author=1&pricing=1')
      }}>
        View more information of this post!
      </button>

    </div>
  )
}
Run Code Online (Sandbox Code Playgroud)

我阅读了 SWR 的文档,我知道 mutate 的键应该与 useSWR() 中的键相同,但在我的情况下需要更多查询参数来获取相应的数据

我怎么解决这个问题?请帮助我!

jul*_*ves 17

我不建议mutate在这种情况下使用,因为key您想要在突变中使用的(URL)与原始的不同。当mutate被调用时,它将更新缓存,'/api/post'然后该缓存将包含'/api/post?author=1&pricing=1'其中的数据。

作为替代方案,我建议您key在调用中创建一个数组useSWR,以便可以将多个参数传递给fetcher.

const [queryParams, setQueryParams] = useState('')
const { data } = useSWR(['/api/post', queryParams], fetcher)
Run Code Online (Sandbox Code Playgroud)

然后,在按钮onClick处理程序中,您可以更新queryParams状态值以触发重新渲染并使用查询参数发起新请求。

<button onClick={() => {            
    setQueryParams('?author=1&pricing=1')
}}>
    View more information of this post!
</button>
Run Code Online (Sandbox Code Playgroud)

您还需要fetcher稍微修改该函数以接受多个参数,并将传递的查询参数附加到 URL。

const fetcher = (url, queryParams = '') => {
    // Example fetch to demonstrate the logic
    return fetch(`${url}${queryParams}`)
}
Run Code Online (Sandbox Code Playgroud)

通过此更改,您现在为您发出请求的每个 URL 拥有不同的密钥(和缓存数据)。