useEffect 依赖于 Context API。我的代码适用于空数组,但仍会发出警告

useEffect dependency with Context API. My code works fine with empty array but still gives the warning

所以。我从上下文中获取客户作为 initialState,下面的代码来自我的列表组件 (listClients.js or 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();
    }
}, []);

您可以在 useEffect 中声明 clientsRef,对于 updateCloients 函数,您可以在 ContextProvider 中使用 useCallback。完成后,您可以将它们添加为对 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
}, []);

有关详细信息,请查看此 post: