簡體   English   中英

即使在解構之后,React useEffect 也會抱怨缺少依賴項

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

在您將其標記為重復之前 - 請理解我已經嘗試關注 SO 上的大部分文章,但它們似乎都沒有幫助我解決問題,也許我忽略了一些東西,或者我今天腦子放屁了。 所以請原諒我再次提出這個問題。

在我的組件中,我有以下代碼要點。

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

正如您可以從上面的代碼中驗證的那樣,我只在 useEffect 中使用了 teamid。 我沒有使用整個道具對象。 但是,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

請讓我知道我在這里做錯了什么。 任何幫助將不勝感激。

試圖通過currentTeamteamMembersuseEffect

let { currentTeam, teamMembers } = props

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

基本上, 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

完全解構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