【问题标题】:React-query doesn't refresh the componentReact-query 不刷新组件
【发布时间】:2021-12-26 20:59:03
【问题描述】:

我遇到了 react-query 的问题。如果正在获取 integrationDetails 查询,我有一个组件,其中包含显示加载微调器的组件。但是当查询完成获取时,我的组件根本不会更新。我尝试创建状态然后使用它,但问题仍然存在。

UPDATE:组件确实会更新,但子组件不会。

...

  const currentWorkspace = useGetCurrentWorkspaceDetail();
  const integrationDetails = useGetIntegrationDetails();
  useEffect(() => {
    integrationDetails.refetch(); //force refetch the query whenever I enter the page.
//problem persists even if I comment this part out
  }, []);

  useEffect(() => {
    console.log(integrationDetails.isFetching); //this logs true and then false.
  }, [integrationDetails]);

  if (currentWorkspace.isLoading) {
    return (
      <div className={styles.layout}>
        <LoadingSpinner />
      </div>
    );
  }


  return (
    <div className={styles.layout}>
      <div className={styles.rest}>
        <div className={styles.column}>
          <Card>
            <CardTabs tabs={["1"]}>
              <div>
                <h3>Global Tracking Code</h3>
                <div style={{ marginTop: 12 }}>
                  <StatusStripe
                    isLoading={integrationDetails.isFetching}
                    ...
                  />
                </div>
                ...

【问题讨论】:

    标签: reactjs react-query


    【解决方案1】:

    你的第一个 useEffect 就像componentDidMount 一样,它只会在第一次渲染时被调用,因为你在它的第二个参数中传递了一个空列表,即[]。 您可以在第二个 useEffect 中编写逻辑,您可以在其中知道何时获取数据,并且可以在那里进行状态设置或绑定。

    【讨论】:

    • 是的,这就是第一个 useEffect 的作用,就像componentDidMount 一样,并“强制重新获取”查询。
    • 在您的第一个问题中,您是说当查询完成获取结果时,您的组件不会更新。当您已经添加了 fetch 挂钩时,为什么还要尝试在 componentDidMount 中重新获取它。这仍然没有意义。如果您的孩子没有被重新渲染,那么显然这意味着您传递给该组件的道具没有改变。您可能还会查看为查询添加的缓存策略。希望您可以尝试仅网络或无缓存作为您的缓存策略。
    • 当我在第二个使用效果钩子中检查时,我传递的道具正在发生变化,并且只是在组件中将其显示为文本。除了子组件之外,一切都发生了变化。
    • 你需要展示你的自定义钩子在做什么,否则,它不可能告诉。没有必要调用refetch,如果您的查询是陈旧的,这就是refetchOnMount 将为您做的事情(默认情况下该标志为真),所以除非您设置了不同的staleTime 或关闭那个标志,它不应该被需要。
    猜你喜欢
    • 2023-02-03
    • 2021-12-17
    • 2021-05-29
    • 1970-01-01
    • 1970-01-01
    • 2019-01-12
    • 2018-04-22
    • 2018-01-05
    • 2018-12-17
    相关资源
    最近更新 更多