正文从这开始~

总览

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的更多相关文章

  1. React报错之React Hook 'useEffect' is called in function

    正文从这开始~ 总览 为了解决错误"React Hook 'useEffect' is called in function that is neither a React function ...

  2. React报错之React hook 'useState' cannot be called in a class component

    正文从这开始~ 总览 当我们尝试在类组件中使用useState 钩子时,会产生"React hook 'useState' cannot be called in a class compo ...

  3. React报错之React hook 'useState' is called conditionally

    正文从这开始~ 总览 当我们有条件地使用useState钩子时,或者在一个可能有返回值的条件之后,会产生"React hook 'useState' is called conditiona ...

  4. React报错之Invalid hook call

    正文从这开始~ 总览 导致"Invalid hook call. Hooks can only be called inside the body of a function compone ...

  5. React报错之react component changing uncontrolled input

    正文从这开始~ 总览 当input的值被初始化为undefined,但后来又变更为一个不同的值时,会产生"A component is changing an uncontrolled in ...

  6. react 报错的堆栈处理

    react报错 Warning: You cannot PUSH the same path using hash history 在Link上使用replace 原文地址https://reactt ...

  7. 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 ...

  8. 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 由于 ...

  9. React报错 :browserHistory doesn't exist in react-router

    由于版本问题,React中history不可用 import { hashHistory } from 'react-router' 首先应该导入react-router-dom包: import { ...

随机推荐

  1. 配置中心的设计-nacos vs apollo

    简介 前面我们分析了携程的 apollo(见 详解apollo的设计与使用),现在再来看看阿里的 nacos. 和 apollo 一样,nacos 也是一款配置中心,同样可以实现配置的集中管理.分环境 ...

  2. 论文解读(ARVGA)《Learning Graph Embedding with Adversarial Training Methods》

    论文信息 论文标题:Learning Graph Embedding with Adversarial Training Methods论文作者:Shirui Pan, Ruiqi Hu, Sai-f ...

  3. zigbee技术数传电台在石油探井状态监测系统

    石油探井分布分散,数量众多,出现异常现象需及时处理.人工巡视耗时长.时效性差:有线传输存在布线繁琐.成本高.现场无移动网络覆盖等诸多缺点. 现需要一种支持大量接入.覆盖范围广.数据传输高效且有数据中心 ...

  4. 用一个性能提升了666倍的小案例说明在TiDB中正确使用索引的重要性

    背景 最近在给一个物流系统做TiDB POC测试,这个系统是基于MySQL开发的,本次投入测试的业务数据大概10个库约900张表,最大单表6千多万行. 这个规模不算大,测试数据以及库表结构是用Dump ...

  5. Centos使用crontab自动定时备份mysql的脚本

    在我们网站上线之后免不了需要备份数据库,为什么要备份呢?我给大家列出了3个理由. 1.防止数据丢失 2.防止数据改错了,可以用来恢复 3.方便给客户数据 以 上几点告诉我们要经常备份,当然我今天给大家 ...

  6. 【Redis】Redis Cluster初始化及PING消息的发送

    Cluster消息类型定义 #define CLUSTERMSG_TYPE_PING 0 /* Ping消息类型,节点间进行通信交换信息的消息 */ #define CLUSTERMSG_TYPE_P ...

  7. 3.shell脚本循环试题

    shell脚本循环试题 1.计算从1到100所有整数的和 #!/bin/bash a=0 for i in {1..100} #1到100 #每次循环变量i的值也为循环次数 do a=$[ $a + ...

  8. 十分钟快速实战Three.js

    前言 本文不会对Three.js几何体.材质.相机.模型.光源等概念详细讲解,会首先分成几个模块给大家快速演示一盒小案例.大家可以根据这几个模块快速了解Three.js的无限魅力.学习 我们会使用Th ...

  9. Python自动化办公:将文本文档内容批量分类导入Excel表格

    序言 (https://jq.qq.com/?_wv=1027&k=GmeRhIX0) 它来了,它又来了. 本文实现用Python将文本文件自动保存到Excel表格里面去. 需求 将锦江区.t ...

  10. 开发人员要学的Docker从入门到日常命令使用(通俗易懂),专业运维人员请勿点!

    一.介绍Docker  1.引言 问题1:开发人员告诉测试说自己的项目已经做好了,给你一个发布包,你去测试吧. ## 测试人员,为什么我运行会报错? ## 开发人员说,我本地运行没有问题呀!   解答 ...