简体   繁体   English

即使在解构之后,React useEffect 也会抱怨缺少依赖项

[英]React useEffect is complaining about missing dependency even after destructuring

Before you mark this as a duplicate - please understand that I have tried following most of the articles here on SO but none of them seem to help me out, perhaps I am overlooking something or I am having a brain fart today.在您将其标记为重复之前 - 请理解我已经尝试关注 SO 上的大部分文章,但它们似乎都没有帮助我解决问题,也许我忽略了一些东西,或者我今天脑子放屁了。 So please excuse me for asking this question again.所以请原谅我再次提出这个问题。

In my component , I have the following code gist.在我的组件中,我有以下代码要点。

  let { teamid } = props.currentTeam
  useEffect(() => {
    if (teamid) {
      props.teamMembers(teamid);
    }
  }, [teamid]);

As you can verify from the code above , I am only using teamid in my useEffect.正如您可以从上面的代码中验证的那样,我只在 useEffect 中使用了 teamid。 I am not using the entire props object.我没有使用整个道具对象。 However, React stil complains with this message但是,React 仍然抱怨此消息

React Hook useEffect has a missing dependency: 'props'. Either include it or remove the dependency array. However, 'props' will change when *any* prop changes, so the preferred fix is to destructure the 'props' object outside of the useEffect call and refer to those specific props inside useEffect react-hooks/exhaustive-deps

Please let me know what I am doing wrong here.请让我知道我在这里做错了什么。 Any help will be well appreciated.任何帮助将不胜感激。

Try to pass currentTeam and teamMembers to useEffect试图通过currentTeamteamMembersuseEffect

let { currentTeam, teamMembers } = props

  useEffect(() => {
    if (currentTeam.teamid) {
      teamMembers(currentTeam.teamid);
    }
  }, [currentTeam, teamMembers]);

Basically what the react-hooks/exhaustive-deps warning is telling you is that you're still referencing the props object within the effect, which you are - you're not destructuring the props item out fully:基本上, react-hooks/exhaustive-deps警告告诉您的是,您仍在引用效果中的props对象,您就是这样 - 您没有完全解构道具项目:

let { teamid } = props.currentTeam
useEffect(() => {
  if (teamid) {
    props.teamMembers(teamid); // PROPS STILL REFERENCED - ISSUE
  }
}, [teamid]); // NO DEPENDENCY FOR PROPS - ISSUE

Destructure the props object fully and include all the dependencies - with this the props object can update, and if the currentTeam or teamMembers properties don't change then your effect doesn't either:完全解构props对象并包含所有依赖项 - 这样props对象可以更新,如果currentTeamteamMembers属性没有改变,那么你的效果也不会:

const { currentTeam, teamMembers } = props // FULLY DESTRUCTURED
  
useEffect(() => {
  if (currentTeam.teamid) {
    teamMembers(currentTeam.teamid)
  }
}, [currentTeam.teamid, teamMembers]) // NO PROPS DEPENDENCIES

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM