英文:
useParams value is executing useEffect when params constant is indise of array dependecies and I´m resizing app page
问题
这个useEffect
在每次调整页面大小时都会执行。video
是一个数据库文档。
import { useParams } from "react-router-dom";
const params = useParams();
useEffect(() => {
if (
(params.id && !video) ||
(!!params.id && !!video && params.id !== video?._id)
) {
dispatch(addViewVideo({ _id: params.id }));
dispatch(getVideo({ _id: params.id }));
}
}, [params]);
英文:
This useEffect is executed every time I resize my page. video is a DB document
import { useParams } from "react-router-dom";
const params = useParams();
useEffect(() => {
if (
(params.id && !video) ||
(!!params.id && !!video && params.id !== video?._id)
) {
dispatch(addViewVideo({ _id: params.id }));
dispatch(getVideo({ _id: params.id }));
}
}, [params]);
答案1
得分: 0
useParams
中的params
引用很可能在每次渲染周期中都是一个新的对象引用。由于我只从params
对象中看到了params.id
作为唯一的依赖项,所以params.id
应该是依赖项,而不是整个params
对象。同时,似乎video
也是一个缺失的依赖项,应该被添加。
示例:
const { id } = useParams();
useEffect(() => {
if (
(id && !video) ||
(!!id && !!video && id !== video?._id)
) {
dispatch(addViewVideo({ _id: id }));
dispatch(getVideo({ _id: id }));
}
}, [id, video]);
英文:
The useParams
params
reference is likely a new object reference each render cycle. Since params.id
is the only dependency I see from the params
object, params.id
should be the dependency, not the entire params
object. It also appears that video
is a missing dependency and should be added.
Example:
const { id } = useParams();
useEffect(() => {
if (
(id && !video) ||
(!!id && !!video && id !== video?._id)
) {
dispatch(addViewVideo({ _id: id }));
dispatch(getVideo({ _id: id }));
}
}, [id, video]);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论