首页 > 解决方案 > useEffect 与 Context API 的依赖关系。我的代码适用于空数组,但仍然给出警告

问题描述

所以。我从 context 作为 initialState 获取客户端,下面的代码来自我的列表组件(listClients.js 或 smth)。我使用从 firebase 获取的数据更新上下文。使用空数组作为依赖项,一切正常。我在列表组件中列出了我的最终数组。但是 eslint 仍然说我应该将“clientsRef”和“updateClients”添加到依赖项中,但这会导致无限循环。那我该怎么办呢?对这个警告闭上眼睛?

const { clients, removeClient, updateClients } = useContext(ClientsContext);
const collection = 'clients';
const clientsRef = firestore.collection('clients').orderBy('createdAt', 'desc');


useEffect(() => {

    const unsubscribeFromSnapshot = clientsRef.onSnapshot(async snapshot => {
        const clientsMap = convertSnapshotToMap(snapshot);
        updateClients(clientsMap);     

    });

    return () => {
        unsubscribeFromSnapshot();
    }
}, []);

标签: reactjsfirebasereact-contextuse-context

解决方案


您可以在 useEffect 中声明 clientsRef,对于 updateCloients 函数,您可以useCallback在 ContextProvider 中使用。完成后,您可以将它们作为依赖项添加到 useEffect

const { clients, removeClient, updateClients } = useContext(ClientsContext);



useEffect(() => {
    const collection = 'clients';
     const clientsRef = firestore.collection('clients').orderBy('createdAt', 'desc');
    const unsubscribeFromSnapshot = clientsRef.onSnapshot(async snapshot => {
        const clientsMap = convertSnapshotToMap(snapshot);
        updateClients(clientsMap);     

    });

    return () => {
        unsubscribeFromSnapshot();
    }
}, []);

在 ClientContext 提供者中

const updateClients = useCallback(() => {
   // logic here
}, []);

但是,如果您确定只希望 useEffect 中的逻辑运行一次而不是稍后运行,则可以禁用警告

// eslint-disable-next-line react-hooks/exhaustive-deps

前任:

useEffect(() => {

    const unsubscribeFromSnapshot = clientsRef.onSnapshot(async snapshot => {
        const clientsMap = convertSnapshotToMap(snapshot);
        updateClients(clientsMap);     

    });

    return () => {
        unsubscribeFromSnapshot();
    }
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

有关更多详细信息,请查看此帖子:

使用 useEffect React Hook 时如何修复缺少的依赖警告?


推荐阅读