繁体   English   中英

React Hook useCallback 缺少依赖项。 要么包含它,要么移除依赖数组 react-hooks/exhaustive-deps

[英]React Hook useCallback has a missing dependency. Either include it or remove the dependency array react-hooks/exhaustive-deps

我在我的组件中使用了useEffect来执行异步 function。

 useEffect(() => {
    scoreRequest(answers);
  }, [answers]);

然后我得到这个警告:

React Hook useCallback has a missing dependency: 'scoreRequest'. Either include it or remove the dependency array  react-hooks/exhaustive-deps

我使用useCallback来避免这个警告:

const getScore = useCallback(() => {
  scoreRequest(answers);
  }, [answers]);

  useEffect(() => {
    scoreRequest(answers);
  }, [answers]);

但仍然得到同样的错误。 但是,我发现了一个类似的问题,并且在答案中提到了将 function 声明为 useEffect 或者我可以禁用该规则。 function scoreRequest()在另一个文件中声明,我不想将它与我的组件混合。

export const scoreRequest = (answers: IAnswer[]): ThunkAction<void, AppState, null, Action<string>> => {
  return async (dispatch: Dispatch) => {
    dispatch(startScoreRequest());
    getScoreApi(answers).then((response: AxiosResponse) => {
      const { data } = response;
      const answer = {
        scoreLabel: data.message,
        userScore: data.result.userScore,
        totalScore: data.result.totalScore,
        emoji: data.result.emoji,
        scoreLabelColor: data.result.scoreLabelColor
      };
      dispatch(successScore(answer));
    }, (error: AxiosError) => {
      let errorMessage = "Internal Server Error";
      if (error.response) {
        errorMessage = error.response.data.error;
      }
      dispatch(failScore(errorMessage));
      dispatch(errorAlert(errorMessage));
    });
  };
};

有什么解决方案可以解决此警告吗?

当接收函数作为props时,你应该在你的依赖数组中明确声明它,问题是函数每次渲染都会改变。 从您的代码中我可以看到scoreRequest是一个动作创建者。 您可以将其导入组件外部并像这样dispatch

import { actionCreator } from './actions'
import { useDispatch } from 'react-redux'

const Component = () =>{
    const dispatch = useDispatch()

    useEffect(() =>{
        dispatch(actionCreator(answers))
    },[dispatch, answers])
}

这将避免es-lint警告,导致你的动作创建者将它导入到你的组件之外,并dispatch它被记忆,因此它不会改变每个渲染。 React-redux 甚至提到如果你需要通过道具传递一个动作创建者你应该先记住它

当使用 dispatch 将回调传递给子组件时,建议使用 useCallback 对其进行记忆,否则子组件可能会由于引用的更改而不必要地呈现。

暂无
暂无

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

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