设计 React Hooks 防止 react-hooks/exhaustive-deps 警告

IT技术 javascript reactjs functional-programming react-hooks
2021-05-04 00:50:33

我正在设计一个钩子,以便仅在钩子依赖项发生变化时才获取数据。它按预期工作,但我收到了 linter 警告:

React Hook useEffect was passed a dependency list that is not an array literal. This means we can't statically verify whether you've passed the correct dependencies.

React Hook useEffect has missing dependencies: 'data', 'errorHandler', 'route', and 'successHandler'. Either include them or remove the dependency array. If 'successHandler' changes too often, find the parent component that defines it and wrap that definition in useCallback. 

据我所知,我不想在我的依赖项中包含所有这些变量,因为我不想在这些变化时触发这个钩子,我只想在我传递的依赖项发生变化时触发它。

问题: 我如何useFetch()以符合 hooks linter 标准的方式设计hook(如果我的设计模式不符合标准,请详细说明应该如何最好地实现)。

我的useFetch()

function useFetch(
    {
        route,
        data = {},
        successHandler,
        errorHandler,
    },
    dependencies = []) {
    const [loading, setLoading] = useState(true);
    useEffect(() => {
        setLoading(true);
        postJson({route}, data)
            .then(
                res => {
                    if(isFunction(successHandler)) successHandler(res);
                },
                ({responseJSON: err}) => {
                    if(isFunction(errorHandler)) {
                        errorHandler(err);
                    } else {
                        notify({text: err.message || messages.saveFailed(), cssClass: 'error'});
                    }
                }
            )
            .finally(() => {
                setLoading(false);
            });
    }, dependencies);
    return loading;
}

组件使用 useFetch()

function MyComponent({data, selectedReviewId, setField}) {
    const loading = useFetch({
        route: 'foo.fetchData',
        data: {crrType, clientId, programId, userId},
        successHandler: d => setField([], d) // setField() will set data with the value fetched in useFetch() 
    }, [selectedReviewId]);

    return loading ? <SpinnerComponent/> : <div>{data.foo}</div>;
}
2个回答

您已将依赖项作为数组传递,但在接收端,它本质上是一个指向数组的单个变量。Lint 规则useEffect()要求您在方括号中传递依赖项,就像在以下代码中所做的那样。

现在一些技术性的东西。记住是什么产生了警告。它是从语法上检查代码的 lint。它不涉及语义。从语义上讲,您的依赖项列表是正确的,因为您正在传递一个数组,但在语法上,它没有作为数组传递,即它是一个未在方括号中传递的单个变量(像这样[dependencies])(这是 lint 正在寻找的东西)。所以为了满足 lint,你应该写:

useEffect(
  () => { // implementation of function },
  [dependencies]
);

此外,当您发送依赖项数组时,您还可以使用扩展运算符,如下所示:

useEffect(
  () => { // implementation of function },
  [...dependencies]
);

这将通过 Babel 转译器在数组运算符内传播数组元素。Lint 也将保持安静。

eslint警告是正确的-你应该包括那些与依赖。例如,在您的MyComponentifdata更改中,并且它不在您的依赖项列表中,您的useEffect钩子将调用 fetch will outdated data

这同样适用于其他人 - 建议将这些添加到您的依赖项列表中。

对于第一个错误,它可能没问题 - 即使不理想。您有一个动态依赖项列表 -eslint无法确定其中是否包含所有必需的内容。

您的解决方案可能会奏效 - 但它非常脆弱。如果您dependencies碰巧发生变化(例如附加元素或删除的元素)