正文从这开始~

总览

useEffect钩子使用了一个我们没有包含在其依赖数组中的变量或函数时,会产生"React Hook useEffect has a missing dependency"警告。为了解决该错误,禁用某一行的eslint规则,或者将变量移动到useEffect钩子内。

这里有个示例用来展示警告是如何发生的。

  1. // App.js
  2. import React, {useEffect, useState} from 'react';
  3. export default function App() {
  4. const [address, setAddress] = useState({country: '', city: ''});
  5. // ️ objects/arrays are different on re-renders
  6. const obj = {country: 'Chile', city: 'Santiago'};
  7. useEffect(() => {
  8. setAddress(obj);
  9. console.log('useEffect called');
  10. // ️ React Hook useEffect has a missing dependency: 'obj'.
  11. // Either include it or remove the dependency array. eslintreact-hooks/exhaustive-deps
  12. }, []);
  13. return (
  14. <div>
  15. <h1>Country: {address.country}</h1>
  16. <h1>City: {address.city}</h1>
  17. </div>
  18. );
  19. }

上述代码片段的问题在于,我们在useEffect钩子内部使用了obj变量,但我们没有在其依赖数组中包含该变量。

最明显的解决方法是将obj变量添加到useEffect钩子的依赖数组中。然而,在本例中,它将导致一个错误,因为在JavaScript中,对象和数组是通过引用进行比较的。

obj变量是一个对象,在每次重新渲染时都有相同的键值对,但它每次都指向内存中的不同位置,所以它将无法通过相等检查并导致无限的重新渲染循环。

在JavaScript中,数组也是通过引用进行比较。

禁用规则

绕过"React Hook useEffect has a missing dependency"警告的一个方法是禁用某一行的eslint规则。

  1. import React, {useEffect, useState} from 'react';
  2. export default function App() {
  3. const [address, setAddress] = useState({country: '', city: ''});
  4. const obj = {country: 'Chile', city: 'Santiago'};
  5. useEffect(() => {
  6. setAddress(obj);
  7. console.log('useEffect called');
  8. // eslint-disable-next-line react-hooks/exhaustive-deps
  9. }, []);
  10. return (
  11. <div>
  12. <h1>Country: {address.country}</h1>
  13. <h1>City: {address.city}</h1>
  14. </div>
  15. );
  16. }

依赖数组上方的注释禁用了单行的react-hooks/exhausting-deps规则。

useEffect钩子的第二个参数传递的是空数组时,只有当组件挂载或者卸载时才会调用。

依赖移入

另一种解决办法是,将变量或者函数声明移动到useEffect钩子内部。

  1. import React, {useEffect, useState} from 'react';
  2. export default function App() {
  3. const [address, setAddress] = useState({country: '', city: ''});
  4. useEffect(() => {
  5. // ️ move object / array / function declaration
  6. // inside of the useEffect hook
  7. const obj = {country: 'Chile', city: 'Santiago'};
  8. setAddress(obj);
  9. console.log('useEffect called');
  10. }, []);
  11. return (
  12. <div>
  13. <h1>Country: {address.country}</h1>
  14. <h1>City: {address.city}</h1>
  15. </div>
  16. );
  17. }

我们把对象的变量声明移到了useEffect钩子里面。这就消除了警告,因为钩子不再依赖对象,对象声明在钩子内部。

依赖移出

另一个可能的解决方案是将函数或变量的声明移出你的组件,这可能很少使用,但最好知道。

  1. import React, {useEffect, useState} from 'react';
  2. // ️ move function/variable declaration outside of component
  3. const obj = {country: 'Chile', city: 'Santiago'};
  4. export default function App() {
  5. const [address, setAddress] = useState({country: '', city: ''});
  6. useEffect(() => {
  7. setAddress(obj);
  8. console.log('useEffect called');
  9. }, []);
  10. return (
  11. <div>
  12. <h1>Country: {address.country}</h1>
  13. <h1>City: {address.city}</h1>
  14. </div>
  15. );
  16. }

这是很有用的,因为每次重新渲染App组件时,变量不会每次都重新创建。该变量在所有渲染中都会指向内存的相同位置,因此useEffect不需要在其依赖数组中跟踪它。

useMemo

另一个解决方案是使用useMemo钩子来得到一个记忆值。

  1. import React, {useMemo, useEffect, useState} from 'react';
  2. export default function App() {
  3. const [address, setAddress] = useState({country: '', city: ''});
  4. // ️ get memoized value
  5. const obj = useMemo(() => {
  6. return {country: 'Chile', city: 'Santiago'};
  7. }, []);
  8. useEffect(() => {
  9. setAddress(obj);
  10. console.log('useEffect called');
  11. // ️ safely include in dependencies array
  12. }, [obj]);
  13. return (
  14. <div>
  15. <h1>Country: {address.country}</h1>
  16. <h1>City: {address.city}</h1>
  17. </div>
  18. );
  19. }

我们使用useMemo钩子得到一个记忆值,该值在渲染期间不会改变。

useMemo钩子接收一个函数,该函数返回一个要被记忆的值和一个依赖数组作为参数。该钩子只有在其中一个依赖项发生变化时才会重新计算记忆值。

useCallback

请注意,如果你正在使用一个函数,你将使用useCallback钩子来获得一个在渲染期间不会改变的记忆回调。

  1. import React, {useMemo, useEffect, useState, useCallback} from 'react';
  2. export default function App() {
  3. const [address, setAddress] = useState({country: '', city: ''});
  4. // ️ get memoized callback
  5. const sum = useCallback((a, b) => {
  6. return a + b;
  7. }, []);
  8. // ️ get memoized value
  9. const obj = useMemo(() => {
  10. return {country: 'Chile', city: 'Santiago'};
  11. }, []);
  12. useEffect(() => {
  13. setAddress(obj);
  14. console.log('useEffect called');
  15. console.log(sum(100, 100));
  16. // ️ safely include in dependencies array
  17. }, [obj, sum]);
  18. return (
  19. <div>
  20. <h1>Country: {address.country}</h1>
  21. <h1>City: {address.city}</h1>
  22. </div>
  23. );
  24. }

useCallback钩子接收一个内联回调函数和一个依赖数组,并返回一个记忆化版本的回调,该回调只在其中一个依赖发生变化时才会改变。

如果这些建议对你都不起作用,你总是可以用注释来消灭警告。

  1. import React, {useEffect, useState} from 'react';
  2. export default function App() {
  3. const [address, setAddress] = useState({country: '', city: ''});
  4. const obj = {country: 'Chile', city: 'Santiago'};
  5. useEffect(() => {
  6. setAddress(obj);
  7. console.log('useEffect called');
  8. // ️ disable the rule for a single line
  9. // eslint-disable-next-line react-hooks/exhaustive-deps
  10. }, []);
  11. return (
  12. <div>
  13. <h1>Country: {address.country}</h1>
  14. <h1>City: {address.city}</h1>
  15. </div>
  16. );
  17. }

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. 开发工具-MySQL下载地址

    更新记录 2022年6月10日 完善标题. 商业版下载 商业版下载地址 https://edelivery.oracle.com/ 使用Oracle账号登录即可下载. 官方下载 https://dev ...

  2. BUUCTF-FLAG

    FLAG 16进制打开没看到有什么东西,使用binwalk分离也没看到其他文件,猜测是否使用lsb隐写方式. StegSolve打开 可以看到是压缩包的文件头,save bin保存为zip文件解压 提 ...

  3. 重学ES系列之函数优化

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  4. PotPlayer播放百度云盘视频

    需要的工具 PotPlayer.油猴tampermonkey.坚果(这个不用下载,有个账号就行) 下载地址:百度网盘 步骤 安装油猴tampermonkey 拖拽Tampermonkey_4.14.c ...

  5. TypeScript ReadonlyArray(只读数组类型) 详细介绍

    1.ReadonlyArray 简介 在TypeScript中,除了Array<T>类型,还有一个ReadonlyArray<T>类型,ReadonlyArray类型和Arra ...

  6. 【Java面试】简单说一下你对序列化和反序列化的理解

    Hi,大家好,我是Mic 一个工作4年的粉丝,投了很多简历 好不容易接到一个互联网公司的面试邀约. 在面试第一轮就被干掉了,原因是对主流互联网技术理解太浅了. 其中就有一个这样的问题:"简单 ...

  7. gitlab和jenkins做持续集成构建教程

    背景介绍 上一个轮回,我花了三篇文章的时间着重向大家介绍了在条件有限的情况下,如果优雅地进行前端发版和迭代.庆七一,热烈庆祝香港回归,人民生活水平越来越好,昨天上午我自掏腰包买了台服务器,决定由冷兵器 ...

  8. 查询效率提升10倍!3种优化方案,帮你解决MySQL深分页问题

    开发经常遇到分页查询的需求,但是当翻页过多的时候,就会产生深分页,导致查询效率急剧下降. 有没有什么办法,能解决深分页的问题呢? 本文总结了三种优化方案,查询效率直接提升10倍,一起学习一下. 1. ...

  9. PTA(BasicLevel)-1023 组个最小数

    一. 问题定义 给定数字 0-9 各若干个.你可以以任意顺序排列这些数字,但必须全部使用.目标是使得最后得到的数尽可能小(注意 0 不能做首位). 例如:给定两个 0,两个 1,三个 5,一个 8,我 ...

  10. Conversation Modeling on Reddit Using a Graph-Structured LSTM

    publish: Transactions of the Association for Computational Linguistics,2016 tasks:  predicting popul ...