【问题标题】:React-Query: Trigger a re-render in component when a query is re-fetched due to a mutation calling invalidateQueries in a sub-componentReact-Query:由于在子组件中调用 invalidateQueries 的突变而重新获取查询时触发组件中的重新渲染
【发布时间】:2021-07-18 09:07:30
【问题描述】:

我在一个 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} />
)

--PostForm--

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 中的查询失效时,我可以看到添加了新帖子的新 GET 请求正在发出,但 我也希望 isLoading 设置为 true 然后为 false 并且用于触发 Posts 中 useEffect 钩子的依赖数组

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

【问题讨论】:

    标签: reactjs react-hooks use-effect react-query


    【解决方案1】:

    isLoading 仅设置为true,前提是在获取之前没有数据,例如当您第一次加载应用程序时。如果已经有数据(包括缓存数据),并且你正在做后续的refetching,你可以使用isFetching来指示fetching状态。

    【讨论】:

      猜你喜欢
      • 2021-12-01
      • 1970-01-01
      • 2020-06-02
      • 2023-02-03
      • 2019-06-01
      • 1970-01-01
      • 2019-01-31
      • 2020-05-01
      • 1970-01-01
      相关资源
      最近更新 更多