reactjs - 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();
}
}, []);
解决方案
您可以在 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
}, []);
有关更多详细信息,请查看此帖子:
推荐阅读
- antlr - 解析以特定关键字开头和结尾的代码块
- javascript - 是否可以完全用 javascript 构建一个 html 网页?
- c# - 无法在 RavenDB 上查询附件
- performance - 甲骨文商务云首页加载的性能提升
- php - Laravel 8 - 从数据库中计算行数
- python - 通过 Firefox (Python) 保存和重复使用 Selenium 制作的 GMAIL cookie
- reactjs - 删除 url 中的参数以进行 nextjs 重定向
- r - 在 x 轴上制作包含多个变量的深度剖面,包括误差线
- python - Pyspark - 将字符串类型元素数组转换为键值对映射
- kubernetes - Pod 无法访问 kubernets clusterIP 服务 (10.96.0.1)