反应,网址更改后无法运行逻辑效果

发布于 2025-02-11 01:53:12 字数 825 浏览 1 评论 0 原文

我的组件中有一个:

const [filtersFetched, setFiltersFetched] = React.useState(false);
useEffect(() => {
  if (history.location.search.includes("publisher_id=") && !filtersFetched) {
    fetchAllAxiosResponse <
      API.Publisher >
      (CatalogService.getPublishers, new URLSearchParams(), 1500)
        .then((data) => {
          setPublishers(data);
          setFiltersFetched(true);
        })
        .catch((err) => {
          setFiltersFetched(true);
        });
  }
}, [filtersFetched, history.location]);

const asyncFilters = {
  publisher_id: filtersFetched,
};

想法是 useffect 每次历史记录堆栈更改时都运行,但是如果它已经运行一次,则不应再次运行。因此,在第一个条件下,!过滤

我如何避免?因为每次更改位置(我在应用程序的另一部分中替换URL)时, filtersfetched 将重置为 false ,整个获取再次发生。

I have this in my component:

const [filtersFetched, setFiltersFetched] = React.useState(false);
useEffect(() => {
  if (history.location.search.includes("publisher_id=") && !filtersFetched) {
    fetchAllAxiosResponse <
      API.Publisher >
      (CatalogService.getPublishers, new URLSearchParams(), 1500)
        .then((data) => {
          setPublishers(data);
          setFiltersFetched(true);
        })
        .catch((err) => {
          setFiltersFetched(true);
        });
  }
}, [filtersFetched, history.location]);

const asyncFilters = {
  publisher_id: filtersFetched,
};

The idea is that the useEFfect runs every time that the history stack changes, but if it has already been run once, it should not run again. Hence the !filtersFetched in the first condition

How can I avoid that? Because every time I change the location (I'm replacing the url in other part of the app), filtersFetched is reset to false, and the whole fetch happens again.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

濫情▎り 2025-02-18 01:53:12

这是发生的,因为每当您更改URL时,组件就会被卸载。当您回来时,它是一个新的组件,这意味着 filtersfetched 状态将处于其初始值。我认为您是这样宣布的:

const [filtersFetched, setFiltersFetched] = useState(false);

这是React的正常行为。如果对您真的很重要的是,它不应在更改URL之后在MORT上运行,则可以使用 localStorage 记住 filtersfetched 的值。为此,将您的更改为:

useEffect(() => {
  if (history.location.search.includes("publisher_id=") && !filtersFetched) {
    fetchAllAxiosResponse <
      API.Publisher >
      (CatalogService.getPublishers, new URLSearchParams(), 1500)
        .then((data) => {
          setPublishers(data);
        })
        .catch((err) => {
          console.log(err);
        })
        .finally(() => {
          setFiltersFetched(true);
          localStorage.setItem("filtersFetched", JSON.stringify(true));
        });
  }
}, [filtersFetched, history.location]);

并设置 filtersfetched 的初始值,而不是以下内容,而不是您之前的内容:

const initialFiltersFetchedValue = localStorage.getItem("filtersFetched")
  ? JSON.parse(localStorage.getItem("filtersFetched"))
  : false;
const [filtersFetched, setFiltersFetched] = useState(initialFiltersFetchedValue);

或 @dilshan所说,您可以使用上下文它包含您的应用程序,将上述逻辑放置在其中。另外,您可以使用一个库,例如 react Query 来缓存您的http请求。

Thats's happening because whenever you change the url, the component gets unmounted. And when you come back, it's a fresh component, which means filtersFetched state will be at its initial value. I assume you declared it like this:

const [filtersFetched, setFiltersFetched] = useState(false);

That's the normal behaviour in React. If it's really important for you that it shouldn't run on mount after url change, you could use localStorage to remember the value of filtersFetched. For that change your useEffect to:

useEffect(() => {
  if (history.location.search.includes("publisher_id=") && !filtersFetched) {
    fetchAllAxiosResponse <
      API.Publisher >
      (CatalogService.getPublishers, new URLSearchParams(), 1500)
        .then((data) => {
          setPublishers(data);
        })
        .catch((err) => {
          console.log(err);
        })
        .finally(() => {
          setFiltersFetched(true);
          localStorage.setItem("filtersFetched", JSON.stringify(true));
        });
  }
}, [filtersFetched, history.location]);

And set the initial value of filtersFetched like below instead of what you had before:

const initialFiltersFetchedValue = localStorage.getItem("filtersFetched")
  ? JSON.parse(localStorage.getItem("filtersFetched"))
  : false;
const [filtersFetched, setFiltersFetched] = useState(initialFiltersFetchedValue);

Or as @Dilshan said, you could use a context that wraps your app, in which you would put the above logic. Also you could use a library like React Query to cache your HTTP requests.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文