我有一个产生一系列标签的标签输入。使用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
发布评论
评论(1)
这可以做到的一种方法是直接更新查询对象并读取URL的标签,而不是在状态下存储标签。
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.