如何在RTK Query中执行查询时重置Mutation的成功状态
在RTK Query中重置Mutation状态以匹配查询加载状态
嘿,这个需求在RTK Query里有挺直观的实现方式,我给你分享两个常用的方案,你可以根据自己的场景选择:
方案一:利用Mutation的reset()方法 + React useEffect
RTK Query的Mutation Hook会返回一个reset()函数,专门用来重置该Mutation的所有状态(包括isSuccess、error这些)。我们可以通过监听查询的isFetching状态,在它变为true时调用这个方法,就能把productDeleted重置为false了。
代码示例:
import { useEffect } from 'react'; import { useGetProductsQuery, useDeleteProductMutation } from './api/productsApi'; function ProductsComponent() { const { isFetching: isFetchingProducts, data: productsData, refetch } = useGetProductsQuery(""); // 解构出mutation的reset方法 const [ deleteProduct, { isSuccess: productDeleted, error: deleteProductFailed, reset } ] = useDeleteProductMutation(); // 监听查询加载状态,开始加载时重置删除状态 useEffect(() => { if (isFetchingProducts) { reset(); } }, [isFetchingProducts, reset]); // 你的组件逻辑... return ( // 组件JSX内容... ); }
这个方案的好处是完全复用RTK Query内置的状态管理,不需要额外维护自己的state,代码简洁且符合RTK Query的设计思路。
方案二:自定义状态管理(适配更灵活的场景)
如果你希望对状态变化有更精细的控制,可以自己维护一个删除成功的状态,然后在查询开始和删除成功时分别更新它:
import { useState } from 'react'; import { useGetProductsQuery, useDeleteProductMutation } from './api/productsApi'; function ProductsComponent() { const [isProductDeleted, setIsProductDeleted] = useState(false); const { isFetching: isFetchingProducts, data: productsData, refetch } = useGetProductsQuery("", { // 查询开始时重置自定义的删除状态 onStarted: () => { setIsProductDeleted(false); } }); const [ deleteProduct ] = useDeleteProductMutation({ // 删除成功时更新自定义状态 onSuccess: () => { setIsProductDeleted(true); }, // 可选:删除失败时也可以重置状态 onError: () => { setIsProductDeleted(false); } }); // 现在你可以用isProductDeleted代替原来的productDeleted // 组件逻辑... return ( // 组件JSX内容... ); }
这种方式适合你需要在其他地方也控制这个状态的场景,灵活性更高。
个人更推荐第一种方案,因为它更贴合RTK Query的生态,不需要额外的状态维护,代码也更简洁。
内容的提问来源于stack exchange,提问作者Lhon Rafaat Mohammed
相关产品推荐
相关产品推荐

