React报错之React Hook useEffect has a missing dependency
正文从这开始~
总览
当useEffect钩子使用了一个我们没有包含在其依赖数组中的变量或函数时,会产生"React Hook useEffect has a missing dependency"警告。为了解决该错误,禁用某一行的eslint规则,或者将变量移动到useEffect钩子内。
这里有个示例用来展示警告是如何发生的。
// App.js
import React, {useEffect, useState} from 'react';
export default function App() {
const [address, setAddress] = useState({country: '', city: ''});
// ️ objects/arrays are different on re-renders
const obj = {country: 'Chile', city: 'Santiago'};
useEffect(() => {
setAddress(obj);
console.log('useEffect called');
// ️ React Hook useEffect has a missing dependency: 'obj'.
// Either include it or remove the dependency array. eslintreact-hooks/exhaustive-deps
}, []);
return (
<div>
<h1>Country: {address.country}</h1>
<h1>City: {address.city}</h1>
</div>
);
}
上述代码片段的问题在于,我们在useEffect钩子内部使用了obj变量,但我们没有在其依赖数组中包含该变量。
最明显的解决方法是将obj变量添加到useEffect钩子的依赖数组中。然而,在本例中,它将导致一个错误,因为在JavaScript中,对象和数组是通过引用进行比较的。
obj变量是一个对象,在每次重新渲染时都有相同的键值对,但它每次都指向内存中的不同位置,所以它将无法通过相等检查并导致无限的重新渲染循环。
在JavaScript中,数组也是通过引用进行比较。
禁用规则
绕过"React Hook useEffect has a missing dependency"警告的一个方法是禁用某一行的eslint规则。
import React, {useEffect, useState} from 'react';
export default function App() {
const [address, setAddress] = useState({country: '', city: ''});
const obj = {country: 'Chile', city: 'Santiago'};
useEffect(() => {
setAddress(obj);
console.log('useEffect called');
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
<div>
<h1>Country: {address.country}</h1>
<h1>City: {address.city}</h1>
</div>
);
}
依赖数组上方的注释禁用了单行的react-hooks/exhausting-deps规则。
当
useEffect钩子的第二个参数传递的是空数组时,只有当组件挂载或者卸载时才会调用。
依赖移入
另一种解决办法是,将变量或者函数声明移动到useEffect钩子内部。
import React, {useEffect, useState} from 'react';
export default function App() {
const [address, setAddress] = useState({country: '', city: ''});
useEffect(() => {
// ️ move object / array / function declaration
// inside of the useEffect hook
const obj = {country: 'Chile', city: 'Santiago'};
setAddress(obj);
console.log('useEffect called');
}, []);
return (
<div>
<h1>Country: {address.country}</h1>
<h1>City: {address.city}</h1>
</div>
);
}
我们把对象的变量声明移到了useEffect钩子里面。这就消除了警告,因为钩子不再依赖对象,对象声明在钩子内部。
依赖移出
另一个可能的解决方案是将函数或变量的声明移出你的组件,这可能很少使用,但最好知道。
import React, {useEffect, useState} from 'react';
// ️ move function/variable declaration outside of component
const obj = {country: 'Chile', city: 'Santiago'};
export default function App() {
const [address, setAddress] = useState({country: '', city: ''});
useEffect(() => {
setAddress(obj);
console.log('useEffect called');
}, []);
return (
<div>
<h1>Country: {address.country}</h1>
<h1>City: {address.city}</h1>
</div>
);
}
这是很有用的,因为每次重新渲染App组件时,变量不会每次都重新创建。该变量在所有渲染中都会指向内存的相同位置,因此useEffect不需要在其依赖数组中跟踪它。
useMemo
另一个解决方案是使用useMemo钩子来得到一个记忆值。
import React, {useMemo, useEffect, useState} from 'react';
export default function App() {
const [address, setAddress] = useState({country: '', city: ''});
// ️ get memoized value
const obj = useMemo(() => {
return {country: 'Chile', city: 'Santiago'};
}, []);
useEffect(() => {
setAddress(obj);
console.log('useEffect called');
// ️ safely include in dependencies array
}, [obj]);
return (
<div>
<h1>Country: {address.country}</h1>
<h1>City: {address.city}</h1>
</div>
);
}
我们使用useMemo钩子得到一个记忆值,该值在渲染期间不会改变。
useMemo钩子接收一个函数,该函数返回一个要被记忆的值和一个依赖数组作为参数。该钩子只有在其中一个依赖项发生变化时才会重新计算记忆值。
useCallback
请注意,如果你正在使用一个函数,你将使用useCallback钩子来获得一个在渲染期间不会改变的记忆回调。
import React, {useMemo, useEffect, useState, useCallback} from 'react';
export default function App() {
const [address, setAddress] = useState({country: '', city: ''});
// ️ get memoized callback
const sum = useCallback((a, b) => {
return a + b;
}, []);
// ️ get memoized value
const obj = useMemo(() => {
return {country: 'Chile', city: 'Santiago'};
}, []);
useEffect(() => {
setAddress(obj);
console.log('useEffect called');
console.log(sum(100, 100));
// ️ safely include in dependencies array
}, [obj, sum]);
return (
<div>
<h1>Country: {address.country}</h1>
<h1>City: {address.city}</h1>
</div>
);
}
useCallback钩子接收一个内联回调函数和一个依赖数组,并返回一个记忆化版本的回调,该回调只在其中一个依赖发生变化时才会改变。
如果这些建议对你都不起作用,你总是可以用注释来消灭警告。
import React, {useEffect, useState} from 'react';
export default function App() {
const [address, setAddress] = useState({country: '', city: ''});
const obj = {country: 'Chile', city: 'Santiago'};
useEffect(() => {
setAddress(obj);
console.log('useEffect called');
// ️ disable the rule for a single line
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
<div>
<h1>Country: {address.country}</h1>
<h1>City: {address.city}</h1>
</div>
);
}
React报错之React Hook useEffect has a missing dependency的更多相关文章
- React报错之React Hook 'useEffect' is called in function
正文从这开始~ 总览 为了解决错误"React Hook 'useEffect' is called in function that is neither a React function ...
- React报错之React hook 'useState' cannot be called in a class component
正文从这开始~ 总览 当我们尝试在类组件中使用useState 钩子时,会产生"React hook 'useState' cannot be called in a class compo ...
- React报错之React hook 'useState' is called conditionally
正文从这开始~ 总览 当我们有条件地使用useState钩子时,或者在一个可能有返回值的条件之后,会产生"React hook 'useState' is called conditiona ...
- React报错之Invalid hook call
正文从这开始~ 总览 导致"Invalid hook call. Hooks can only be called inside the body of a function compone ...
- React报错之react component changing uncontrolled input
正文从这开始~ 总览 当input的值被初始化为undefined,但后来又变更为一个不同的值时,会产生"A component is changing an uncontrolled in ...
- react 报错的堆栈处理
react报错 Warning: You cannot PUSH the same path using hash history 在Link上使用replace 原文地址https://reactt ...
- git commit -m "XX"报错 pre -commit hook failed (add --no-verify to bypass)问题
在同步本地文件到线上仓库的时候 报错 pre -commit hook failed (add --no-verify to bypass) 当你在终端输入git commit -m "xx ...
- mysql报错Ignoring the redo log due to missing MLOG_CHECKPOINT between
mysql报错Ignoring the redo log due to missing MLOG_CHECKPOINT between mysql版本:5.7.19 系统版本:centos7.3 由于 ...
- React报错 :browserHistory doesn't exist in react-router
由于版本问题,React中history不可用 import { hashHistory } from 'react-router' 首先应该导入react-router-dom包: import { ...
随机推荐
- 史上最全Spring Cloud Alibaba--Nacos教程(涵盖负载均衡、配置管理、多环境切换、配置共享/刷新、灰度、集群)
能够实现Nacos安装 基于Nacos能实现应用负载均衡 能基于Nacos实现配置管理 配置管理 负载均衡 多环境切换 配置共享 配置刷新 灰度发布 掌握Nacos集群部署 1 Nacos安装 Nac ...
- 计算机网络 - OSI 7层网络模型各层对应的功能
应用层 - 负责给应用程序提供统一的接口 表示层 - 负责把数据的解压缩和编码 会话层 - 负责会话的管理(建立和终止) 传输层 - 负责端到端的数据传输 网络层 - 负责数据的路由.转发.分片 数据 ...
- 《Unix 网络编程》14:高级 I/O 函数
高级 I/O 函数 ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ...
- Xilinx DMA的几种方式与架构
DMA是direct memory access,在FPGA系统中,常用的几种DMA需求: 1. 在PL内部无PS(CPU这里统一称为PS)持续干预搬移数据,常见的接口形态为AXIS与AXI,AXI与 ...
- Markdown常见基本语法
标题 -方式一:使用警号 几个警号就是几级标题,eg: # 一级标题 -方式二: 使用快捷键 ctrl+数字 几级标题就选其对应的数字, eg: ctrl+2(二级标题) 子标题 -方式一: 使用星号 ...
- python基础知识-day9(数据驱动)
1.数据驱动的概念 在自动化测试中,需要把测试的数据分离到JSON,YAML等文件中. 2.YAML 的相关知识 YAML 入门教程 分类 编程技术 YAML 是 "YAML Ain't a ...
- RPA工单查询和下载流程机器人
1.登录业务系统,输入用户名和密码 2.进入下载模块 3.输入下载查询条件 4.进入文件明细单 5.下载文件 视频地址:https://www.bilibili.com/video/BV1964y1D ...
- ES5的继承和ES6的继承有什么区别?让Babel来告诉你
如果以前问我ES5的继承和ES6的继承有什么区别,我一定会自信的说没有区别,不过是语法糖而已,充其量也就是写法有区别,但是现在我会假装思考一下,然后说虽然只是语法糖,但也是有点小区别的,那么具体有什么 ...
- c# 怎样能写个sql的解析器
c# 怎样能写个sql的解析器 本示例主要是讲明sql解析的原理,真实的源代码下查看 sql解析器源代码 详细示例DEMO 请查看demo代码 前言 阅读本文需要有一定正则表达式基础 正则表达式基础教 ...
- 虚拟机启动时报’A start job is running for /etc/rc.local .. Compatibility错误。
虚拟机启动时报'A start job is running for /etc/rc.local .. Compatibility错误. 问题已经存在很长时间了,但是不影响ssh登录,遂置之未理. 经 ...