更新NextJS查询字符串时,请防止使用效应无限循环

发布于 2025-01-31 02:29:55 字数 921 浏览 2 评论 0 原文

我有一个产生一系列标签的标签输入。使用NextJS的UserOuter,我想在添加时将这些标签添加为查询字符串参数。我还需要保留当前查询字符串参数,因为其他过滤器,搜索和分页需要保留。

这是我目前的工作方式。

const router = useRouter();
const { query } = router;
const [tags, setTags] = useState([]);

useEffect(() => {
  router.push({
    query: {
      ...query,
      tags,
    },
  });
}, [tags, router, query]);

return (
  <>
    <TagInput tags={tags} setTags={setTags} placeholder="Search by tags" />
  </>
);

但是,这会导致无限渲染,因为使用效果更新了 query ,但也将 Query 作为依赖关系。如果我将 QUERY 作为依赖项删除,则可以正常工作,但是我会发现丢失的依赖项绑布错误。

编辑:这是一个代码框,其中一个最小的示例可以重现问题。它的工作原样,但是如果您输入 QUERY 依赖关系,则无限循环。

I have a tag input that produces an array of tags. Using NextJs's useRouter, I want to add those tags as query string params as they are added. I also need to preserve the current query string params, since other filters, searches, and pagination need to remain.

Here is how I'm currently doing it.

const router = useRouter();
const { query } = router;
const [tags, setTags] = useState([]);

useEffect(() => {
  router.push({
    query: {
      ...query,
      tags,
    },
  });
}, [tags, router, query]);

return (
  <>
    <TagInput tags={tags} setTags={setTags} placeholder="Search by tags" />
  </>
);

However, this causes an infinite render since the useEffect updates the query but also has query as a dependency. If I remove query as a dependency, it works fine, but I get the missing dependency linting error.

Edit: Here is a codesandbox with a minimal example that reproduces the issue. It works as is, but if you uncomment the query dependency, infinite loop.
https://codesandbox.io/s/next-js-dynamic-routing-forked-rlxuqh?file=/pages/index.js

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

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

发布评论

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

评论(1

半透明的墙 2025-02-07 02:29:55

这可以做到的一种方法是直接更新查询对象并读取URL的标签,而不是在状态下存储标签。

const router = useRouter();
const { query } = router;

const setTags = useCallback((tags) => {
  router.push({
    query: {
      ...query,
      tags
    }
  });
}, [router, query]);

return (
  <>
    <TagInput tags={query.tags || []} setTags={setTags} placeholder="Search by tags" />
  </>
);

One way this can be done is to directly update the query object and read the tags from the url, rather than storing the tags in state.

const router = useRouter();
const { query } = router;

const setTags = useCallback((tags) => {
  router.push({
    query: {
      ...query,
      tags
    }
  });
}, [router, query]);

return (
  <>
    <TagInput tags={query.tags || []} setTags={setTags} placeholder="Search by tags" />
  </>
);

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