【问题标题】:useEffect dependency with Context API. My code works fine with empty array but still gives the warninguseEffect 与 Context API 的依赖关系。我的代码适用于空数组但仍然发出警告
【发布时间】:2020-06-01 05:33:09
【问题描述】:

所以。我从 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();
    }
}, []);

【问题讨论】:

    标签: reactjs firebase react-context use-context


    【解决方案1】:

    您可以在 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
    }, []);
    

    更多详情请查看此帖:

    How to fix missing dependency warning when using useEffect React Hook?

    【讨论】:

    • 像魅力一样工作!谢谢。使用回调岩石。照你说的做后,只有 [updateClients] 就够了。
    • 很高兴有帮助 :-)
    猜你喜欢
    • 2021-07-12
    • 1970-01-01
    • 2019-12-14
    • 1970-01-01
    • 2021-01-16
    • 1970-01-01
    • 2021-08-13
    • 2021-12-07
    • 1970-01-01
    相关资源
    最近更新 更多