使用效果依赖与上下文 API.我的代码在空数组下工作正常,但仍然给出警告



所以。我从上下文中获取客户端作为 initialState,下面的代码来自我的列表组件(列表客户端.js或 smth(。我使用从火库获取的数据更新上下文。实际上,使用空数组作为依赖项可以正常工作。我在我的列表组件上列出了我的最后一个数组。但是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。完成此操作后,您可以将它们添加为依赖项以使用效果

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();
}
}, []);

在客户端上下文提供程序中

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时修复缺少依赖警告?

最新更新