React useEffect 抱怨即使在解构后也缺少依赖

React useEffect is complaining about missing dependency even after destructuring

在您将此标记为重复之前 - 请理解我已经尝试关注此处关于 SO 的大部分文章,但其中 none 似乎对我有所帮助,也许我忽略了某些东西或者我有今天脑放屁。所以请原谅我再问这个问题。

在我的组件中,我有以下代码要点。

  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

请让我知道我在这里做错了什么。任何帮助将不胜感激。

尝试将 currentTeamteamMembers 传递给 useEffect

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