useParams value is executing useEffect when params constant is indise of array dependecies and I´m resizing app page

huangapple go评论78阅读模式
英文:

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]);

huangapple
  • 本文由 发表于 2023年6月5日 23:50:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76408087.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定