React-Query:由于在子组件中调用 invalidateQueries 的突变而重新获取查询时,在组件中触发重新渲染

React-Query: Trigger a re-render in component when a query is re-fetched due to a mutation calling invalidateQueries in a sub-component

我在 Posts 组件中使用 react-query,它呈现一个 PostForm 组件,后跟一个 PostView 组件列表。

--帖子--

const [ isLoading, data ] = useQuery("get_posts", {...}, )

const [ userPosts, setUserPosts] = useState([]);
const [ isReady, setIsReady ] = useState(false);

useeffect(() => {
    newPosts = ..do some things with the data
    setUserPosts(newPosts)
    setIsReady(true);
}, [isLoading])

return !isReady ? null : (
    <PostForm />
    posts.current.map(post => <PostView key={post.id} Content={post} />
)

--邮政表格--

const mutation = useMutation(
    () => { ... },
    { onSuccess: queryClient.invalidateQueries("get_posts")}
)

const submitHandler = e => {
    const newPost = ...
    mutation.mutate(newPost)
}

return ( a form wired to the submitHandler )

当在 PostForm 中调用突变并且 Posts 中的查询失效时,我可以看到使用新添加的 post 发出的新 GET 请求,但是 我也希望 isLoading被设置为 true 然后 false 并触发 useEffect 钩子的依赖数组 in Posts.

重新获取查询时,isLoading 值不是被重置了吗?当突变使之前的查询结果无效时,如何在我的 Posts 组件上触发重新呈现?

isLoading 仅在获取之前没有数据的情况下设置为 true,例如您第一次加载应用时。如果已经有数据(包括缓存数据),并且你在做后续的重新获取,你可以使用isFetching来表示获取状态。