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 { ...
随机推荐
- java和.net 双语言开发框架,开源的PaaS平台
当下,我国国内的PaaS平台正在蓬勃发展,各式各样的PaaS平台层出不穷,但万变不离其宗,一个优秀的PaaS平台总有自己独树一帜或与众不同的地方.那么,首先我们要了解下什么是PaaS平台?PaaS是( ...
- docker安装mysql,开启主从
docker pull mysql:5.7 创建目录/mydata/mysql/log /mydata/mysql/conf /mydata/mysql/data docker run -itd -- ...
- Spring bean到底是如何创建的?(上)
前言 众所周知,spring对于java程序员来说是一个及其重要的后端框架,几乎所有的公司都会使用的框架,而且深受广大面试官的青睐.所以本文就以常见的一个面试题"spring bean的生命 ...
- 区分 python 爬虫或者是写自动化脚本时遇到的 content与text的作用
通常在使用过程中或许我们能够轻而易举的会使用requsts模块中的content 与 text ,从print结果来看根本看不出任何区别: 总结精髓,text 返回的是unicode 型的数据,一般是 ...
- CabloyJS部署了一套演示站点
为了方便大家快速体验和了解CabloyJS的风格和特性,全新部署了一套演示站点.对于初次接触CabloyJS的开发者,不用下载新建项目,就可以直接体验CabloyJS了 在线演示 场景 链接/二维码 ...
- Gitee整改之思考
本文主要内容如下: 1.Gitee是什么? 2.Gitee与Github的区别有哪些? 3.为什么要使用Gitee? 4.Gitee的商业模式是怎样的? 5.Gitee为何会被整改? 6.Gitee这 ...
- go-zero微服务实战系列(五、缓存代码怎么写)
缓存是高并发服务的基础,毫不夸张的说没有缓存高并发服务就无从谈起.本项目缓存使用Redis,Redis是目前主流的缓存数据库,支持丰富的数据类型,其中集合类型的底层主要依赖:整数数组.双向链表.哈希表 ...
- C#中的 Attribute 与 Python/TypeScript 中的装饰器是同个东西吗
前言 最近成功把「前端带师」带入C#的坑(实际是前端带师开始从cocos转unity游戏开发了) 某天,「前端带师」看到这段代码后问了个问题:[这个是装饰器]? [HttpGet] public Re ...
- django--ORM表的多对一关系
多对一关系是什么 Django使用django.db.models.ForeignKey定义多对一关系. ForeignKey需要一个位置参数:与该模型关联的类 class Info(models. ...
- UiPath官方视频Level1
[UiPath官方视频Level1]第一课-UiPath简介https://www.bilibili.com/video/BV1zJ41187vB [UiPath官方视频Level1]第二课-变量和数 ...