reactjs 如何手动执行按钮点击重取?

4szc88ey  于 5个月前  发布在  React
关注(0)|答案(2)|浏览(48)

在我的应用程序中,我使用react-query来处理获取数据。我使用useQuery在我的组件中接收数据。代码如下所示:

const { isLoading, data} = useQuery('albums', fetchAlbums)

   const fetchAlbums = () => {
      const res = await axios.get('/albums')
      return res.data
   }

   return (
      isLoading ? <Spinner /> :
      <div>
         // When clicking this button, check if there is new data from the api endpoint, and if so, set data variable to the new data
         <button>Refetch data</button>

         // Display the data
         {data}
      </div>
   )

字符串
上面的代码工作正常,但是当点击显示的按钮时,它应该检查是否有来自fetchAlbums中指定的endpoint的新数据,如果有来自端点的新数据,更新albumsdata变量并显示新数据。我的问题是,我希望旧的data仍然显示,而refetch发生(即点击按钮后),如果有新的数据,然后替换旧的data显示新的数据.我怎么可能做到这一点?谢谢.

jhiyze9q

jhiyze9q1#

默认情况下,useQuery会在调用它的组件挂载时立即获取,但并不是每个人都希望看到这种行为。

方法1:启用布尔值

您可以使用启用的键并将其设置为false,将默认行为设置为“不”立即获取数据

const { data } = useQuery("comments", fetchComments, {
    enabled: false
  });

字符串
如果我们想使用按钮来触发它,我们可以维护一个状态,它可以是true或false,然后将setEnabled方法传递给按钮。
单击时,查询将提取数据。

const [enabled, setEnabled] = useState(false);
const { data } = useQuery("comments", fetchComments, {
    enabled: enabled
  });
<button onClick={() => setEnabled(true)}>Some Button</button>

方法2:Refetch()

我的首选方法是使用refetch,这是useQuery附带的一种方法,更接近于我们许多人在这个场景中所寻找的功能。
数据不会自动提取。我们已使用enabled:false将其关闭。
然后,我们可以将refetch方法传递给我们的按钮,以便在不切换任何状态的情况下按需获取数据。

export const useComments = () => {
  const { data, refetch } = useQuery("comments", fetchComments, {
    enabled: false
  });
<button onClick={() => refetch()}>Some Button</button>

gmol1639

gmol16392#

我相信你应该做的是call invalidateQueries()使查询无效,然后在下一次呈现组件时,你对useQuery()的调用应该从服务器重新获取数据,而不是从缓存中获取数据。

相关问题