【问题标题】:How to mutate with query params in SWR hook?如何在 SWR 挂钩中使用查询参数进行变异?
【发布时间】:2022-07-16 20:59:58
【问题描述】:

目前我正在使用 SWR 来获取数据,我尝试使用 SWR 的 Mutation 功能重新获取新数据,但是当我通过 key 添加了新的查询参数。

这是我的代码不起作用:

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

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

我该如何解决这个问题? 请帮帮我!

【问题讨论】:

    标签: reactjs swr


    【解决方案1】:

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

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

    const [queryParams, setQueryParams] = useState('')
    const { data } = useSWR(['/api/post', queryParams], fetcher)
    

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

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

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

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

    通过此更改,您现在对每个请求的 URL 都有不同的键(和缓存数据)。

    【讨论】:

    • 很好的答案!谢谢!
    猜你喜欢
    • 2021-08-10
    • 2020-09-13
    • 2021-09-08
    • 2021-11-02
    • 2021-01-24
    • 2020-05-02
    • 2021-03-29
    • 2020-05-16
    • 2022-06-11
    相关资源
    最近更新 更多