如何将其他依赖项传递给React自定义钩子

时间:2020-05-28 19:35:03

标签: reactjs

我正在使用自定义钩子将初始数据加载到组件中。它工作正常,但由于将动态构造的依赖项传递给useEffect挂钩,因此我得到警告: React Hook useEffect传递了一个非数组文字的依赖项列表。这意味着我们无法静态验证您是否已经传递了正确的依赖项

enter image description here

这是我的自定义钩子的代码:

const useApiData = (path: string, dependancies: any[], defaultValue: any) => {
    const client = useApi();
    const modelTemplate = {
        isLoading: true,
        data: defaultValue ? defaultValue : null
    };

    const [model, setModel] = useState(modelTemplate);
    const dependencies: any[] = dependancies ? [...dependancies, client, path, model.isLoading] : [client, path, model.isLoading];

    useEffect(() => {
        if (!model.isLoading) {
            setModel({ isLoading: true, data: null });
        }
        client.get(path).then(data => {
            setModel({ isLoading: false, data: data });
        }).catch(error => {
            //do nothing, errors will be shown in notifications
        });
    }, dependencies);

    return model;
}

这是传递附加依赖项的示例:

const product = useApiData(`/products/${productId}`, [model.reviewAdded]);

在此组件中,我正在显示产品详细信息及其评论。由于产品评级发生更改,我想在添加评论时更新产品详细信息。我可以使用我的自定义钩子来接收警告吗?

1 个答案:

答案 0 :(得分:3)

这是皮棉问题。 根据文件扩展名(* .ts),看来您使用的是ts-lint。 在我的项目中,我有类似的自定义钩子,但我使用es-lint。使用es-lint,我做了下一个:

  1. 通过以下方式禁用钩子内的警告:
const useCustomHook = (deps) => {
  useEffect(() => {
   doStuff(deps)

  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, deps)
}
  1. 将自定义钩子添加到默认验证器,以便es-lint将自定义钩子视为开箱即用的钩子并进行静态检查:

.eslintrc.js

module.exports = {
 rules: {
   'react-hooks/exhaustive-deps': [
     'error',
     {
       additionalHooks: 'useCustomHook',
     },
   ],
 },
}

我相信,您可以为ts-lint做类似的事情

相关问题