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 { ...
随机推荐
- 前端3JS2
内容概要 运算符 流程控制 三元运算符 函数 自定义对象 内置对象 JSON对象 正则对象 内容详情 运算符
- MySQL-3-DML
DML 数据操作语言 插入insert 语法一:insert into 表名(列名,...)values(值1,...): 语法二:insert into 表名 set 列名=值,列名=值,... 插 ...
- MySql查询日周月
常用计算日期的函数 日 date(日期) = CURDATE() 自然周 YEARWEEK(date_format(日期,'%Y-%m-%d') , 1) = YEARWEEK(now() , 1) ...
- Leetcode----<Diving Board LCCI>
题解如下: public class DivingBoardLCCI { /** * 暴力解法,遍历每一种可能性 时间复杂度:O(2*N) * @param shorter * @param long ...
- ansible管理windows主机
1. 在windows开启winrm winrm service 默认都是未启用的状态,先查看状态:如无返回信息,则是没有启动: winrm enumerate winrm/config/listen ...
- VisionPro · C# · 界面显示视觉结果图像
程序界面通过 CogRecordDisplay 控件显示视觉运行结果图像. 按指定图像显示,代码如下: using System; using System.Windows.Forms; using ...
- python带你采集不可言说网站数据,并带你多重骚操作~
前言 嗨喽,大佬们好鸭!这里是小熊猫~ 今天我们采集国内知名的shipin弹幕网站! 这里有及时的动漫新番,活跃的ACG氛围,有创意的Up主. 大家可以在这里找到许多欢乐. 目录(可根据个人情况点击你 ...
- Jenkins + maven + svn 自动部署项目
1.安装Jenkins sudo wget -O /etc/yum.repos.d/jenkins.repo https://pkg.jenkins.io/redhat-stable/jenkins. ...
- ConcurrentHashMap树化链表treeifyBin
private final void treeifyBin(Node<K,V>[] tab, int index) { Node<K,V> b; int n, sc; if ( ...
- idea 内置tomcat jersey 上传文件报403错误
Request processing failed; nested exception is com.sun.jersey.api.client.UniformInterfaceException: ...