javascript - How to use useEffect hook with the dependency list as a specific field in an array of objects? - Stack Overflow

Let's say I have an array like this:[{country: '','cityprovince': '

Let's say I have an array like this:

[
  {
    country: '',
    'city/province': '',
    street: ''
  },
  {
    country: '',
    'city/province': '',
    street: ''
  }
]

How do I have the useEffect() hook run every time the value of the 'country' field in any item inside the array changes?

Let's say I have an array like this:

[
  {
    country: '',
    'city/province': '',
    street: ''
  },
  {
    country: '',
    'city/province': '',
    street: ''
  }
]

How do I have the useEffect() hook run every time the value of the 'country' field in any item inside the array changes?

Share Improve this question edited Nov 18, 2021 at 13:37 Ashish Kamble 2,6254 gold badges22 silver badges29 bronze badges asked Nov 18, 2021 at 13:35 user13841165user13841165 3
  • Do you need like this? codesandbox.io/s/react-hooks-useeffect-forked-1ow31 – Maniraj Murugan Commented Nov 18, 2021 at 13:49
  • I think that is close @ManirajMurugan - but wouldn't it trigger useEffect if street changes too? – Chris Commented Nov 18, 2021 at 13:54
  • 2 Interesting problem, personally I would go with trying to explicitly invoke the code than needs to run when you change an address, say from a onChangeAddress function, rather than trying to react to deep state changes using useEffect – andy mccullough Commented Nov 18, 2021 at 14:16
Add a ment  | 

3 Answers 3

Reset to default 1

Just map the countries into the effect dependency array.

const countries = data.map((x) => x.country);

useEffect(() => {
  console.log(countries);
}, countries);

Normally you wouldn't want to do that, but just to answer your question, it can be done, so let me propose the following assuming your list is called items:

  useEffect(() => {
    
  }, [...items.map(v => v.country)])

What the above code does is to spread all items (with its country property) into the useEffect dependency array.

The reason why this can be adhoc is mainly because React doesn't like to have a variable length of dependency. In the source code, when the length changes, it only appreciates the element change from the existing elements. So you might run into problem if you switch from 1 elements to 2 elements.

However if you have fixed number of elements, this should do what you wanted. Keep in mind the items has to be an array at all time.

NOTE: to acmodate the length issue, maybe we can add an additional variable length to the dependency array :)

  }, [items.length, ...items.map(v => v.country)])

As i mentioned, most of time, you should avoid doing this, instead try to change the entire items every time when an item changes. And let the Item display to optimize, such as React.memo.

I don't think you can specifically tackle it in the dependency array, however, you can do your check inside the useEffect to have the same overall oute.

Basically, the dependency array is passed the full data state, which will trigger the effect every change, then you do a further check if the sub property has changed.

I'm leverage lodash for brevity, but you can run any function to determine if the data has changed.

Codepen: https://codepen.io/chrisk7777/pen/mdMvpvo?editors=0010

const { useState, useEffect, useRef } = React;
const { render } = ReactDOM;
const { isEqual, map } = _;

const App = () => {
  const [data, setData] = useState([
    {
      country: "",
      "city/province": "",
      street: ""
    },
    {
      country: "",
      "city/province": "",
      street: ""
    }
  ]);
  const prevData = useRef(data);

  // hacky updates just to demonstrate the change
  // change country - should trigger useEffect
  const update1 = () => {
    setData((s) => [s[0], { ...s[1], country: s[1].country + "a" }]);
  };

  // change street - should not trigger useEffect
  const update2 = () => {
    setData((s) => [s[0], { ...s[1], street: s[1].street + "a" }]);
  };

  useEffect(() => {
    if (!isEqual(map(prevData.current, "country"), map(data, "country"))) {
      console.log("country changed");
    }

    prevData.current = data;
  }, [data]);

  return (
    <div>
      <button onClick={update1}>change country - trigger effect</button>
      <br />
      <button onClick={update2}>change street - do not trigger effect</button>
    </div>
  );
};

render(<App />, document.getElementById("app"));

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745668746a4639276.html

相关推荐

  • Doxygen常用注释规则

    Doxygen简介Doxygen 是一款在软件开发中广泛使用的文档生成工具。它通过解析类、函数和变量的相关信息,自动从源代码注释生成文档,并以 HTML 和 PDF 等格式输出。通过简化和标准化文档流程,Doxygen 加强了不同编程语言和

    1小时前
    00
  • C#高性能开发之类型系统:从C# 7.0 到C# 14的类型系统演进全景

    自C# 7.0以来,C#语言在类型系统方面引入了众多新数据类型、类型构造和语言特性,以提升性能、类型安全性和开发效率。本文全面整理了从C# 7.0到C# 14.0(截至2025年4月,C# 14.0为预览版)类型系统的新增内容,包括值元组、

    1小时前
    20
  • JetBrains IDEs GO AI:最新coding agent,更智能的编程助手!

    大家好,欢迎来到程序视点!我是你们的老朋友.小二!JetBrains AI现在,AI 几乎无处不在。作为一名资深码农,我一直期待着有更智能、更高效的工具来提高开发的工作效率,并为开发带来更多乐趣,从而让自己从枯燥的CRUD中解放出来!从 2

    1小时前
    10
  • 更正

    之前文章 地表最强基准-ADR1001 中:这个地方有错误业界流量很高的号,百花潭也转载了,不改正的话变成了错误永流传。有读者留言说,恒温控制晶振(OCXO)也有类似的设计:对于某些应用,TCXO(温度补偿)的频率-温度稳定性指标仍无法满足

    1小时前
    10
  • 拿自己的旧电脑搭建了个服务器!

    最近总是想搭建自己的网站,奈何皮夹里空空如也,服务器也租不起,更别说域名了。于是我就寻思能否自己搭建个服务器,还不要钱呢?还真行!!!经过几天的冲浪,我发现有两个免费的建站工具:Apache和Nginx由于两个工具建站方法差不多,所以我就以

    1小时前
    00
  • 从 Arc,Dia,Fellou之后,一码难求,AI 的风刮到了浏览器?

    下午,偶然在群里看到有朋友在问,有没有Dia的邀请码......这是个什么产品??我查了下,原来是将AI与浏览器结合的产品。还有最近爆火的Fellou,也是一个将Agent与浏览器结合起来的东西。自manus之后,浏览器(browser-u

    1小时前
    00
  • 一个让DevOps癫狂的项目一键部署数百个MCP服务器

    背景MCP(Model Context Protocol)是一种新兴的标准化协议,用于管理大型语言模型(LLM)与外部系统之间的上下文交互。随着 AI 技术的快速发展,越来越多的开发者需要将 LLMs 与各种外部工具、API 和数据源集成。

    1小时前
    00
  • RAG 作者:RAG 已死,RAG 万岁!

    Datawhale分享 作者:Douwe Kiela,编译:思考机器本文作者 Douwe Kiela,RAG 论文(Retrieval-Augmented Generation for Knowledge-Intensive NLP Ta

    1小时前
    00
  • minio使用简介

    在云原生和微服务时代,对象存储已成为存储非结构化数据(如图片、日志、备份等)的首选方案。MinIO 是一款高性能、兼容 S3 API 的开源对象存储服务,而它的官方 Go SDK —— minio-go,则可以让你在 Go 语言项目中轻松集

    58分钟前
    00
  • 动态渲染页面智能嗅探:机器学习判定AJAX加载触发条件

    爬虫代理本文提出了一种基于机器学习的智能嗅探机制,革新性地应用于自动判定动态渲染页面中AJAX加载的最佳触发时机。系统架构采用先进模块化拆解设计,由请求分析模块、机器学习判定模块、数据采集模块和文件存储模块四大核心部分构成。在核心代码示例中

    53分钟前
    00
  • Ascend 910b vllm运行报错: cannot import name &#x27;log&#x27; from &#x27;torch.distributed.elastic

    在Ascend 910b上运行vllm报错. ImportError: cannot import name &#x27;log&#x27; from &#x27;torch.distributed.elastic.

    51分钟前
    00
  • WIFI越近信号越强?CST电磁仿真看看

    在数字化浪潮席卷的现代社会,WiFi 早已深度融入日常生活与工作场景,成为不可或缺的关键要素。凭借便捷连接、高速传输的显著优势,WiFi 不仅重塑了人们的生活模式,还极大提升了工作效率。如今,无论是繁忙的办公室、温馨的餐厅,还是疾驰的交通工

    49分钟前
    00
  • 安利一个超强的linux脚本

    想像一个场景,你突然接手管理一个系统,之前对接的人没有留下任何材料,主机上也没有历史命令能够看到之前做了哪些操作。怎么办?今天介绍一个简单的脚本记录linux历史执行记录的方法,可以在现有主机上配置,然后后面主机初始化都配置上。Linux命

    43分钟前
    00
  • Xinstall APP安全加速SDK上线:拒绝卡顿、无惧攻击

    你的 APP 是否遇到过这些场景:用户抱怨 APP 加载缓慢、操作卡顿,尤其在网络高峰期或信号不佳时?重要推广活动期间,服务器突遭 DDoSCC 攻击,导致服务中断、用户无法访问?担心用户数据在传输过程中被窃取、篡改,引发隐私安全风险和信

    41分钟前
    00
  • 业内首次! 全面复现DeepSeek

    机器之心发布机器之心编辑部OpenAI 的 o1 系列和 DeepSeek-R1 的成功充分证明,大规模强化学习已成为一种极为有效的方法,能够激发大型语言模型(LLM) 的复杂推理行为并显著提升其能力。然而,这些推理模型的核心训练方法在其技

    40分钟前
    00
  • DeepMind CEO 放话:未来十年赌上视觉智能,挑战 OpenAI 语言统治地位

    整理|冬梅、核子可乐去年成功斩获诺贝尔奖之后,Demis Hassabis 决定与一位国际象棋世界冠军打场扑克以示庆祝。Hassabis 一直痴迷于游戏,这股热情也成为他 AI 先驱之路上的契机与驱力。近日,做客一档名为《60 分钟》的访

    33分钟前
    00
  • 浅谈国产数据库多租户方案:提升云计算与SaaS的资源管理效率

    近年来,“数据库多租户”这一概念在技术圈内频频出现,成为云计算和SaaS(软件即服务)架构中的重要组成部分。多租户架构不仅为企业提供了高效的资源隔离与共享解决方案,还能大幅降低成本,提高系统的可扩展性与维护效率。很多人认为,它是SaaS模式

    25分钟前
    00
  • MobileNetV2:面向移动端的高效神经网络架构革新——突破轻量化模型的设计边界

    我们倾向于将“移动”与更小、更高效的事物联系起来,所以我原本以为这个网络的设计会占用更少的计算资源,而这正是作者的目标。这篇论文描述了一种专为移动和资源受限环境量身定制的全新神经架构——MobileNetV2。他们强调了MobileNetV

    21分钟前
    00
  • 【一步步开发AI运动APP】八、自定义姿态动作识别检测——之姿态相似度比较

    之前我们为您分享了【一步步开发AI运动小程序】开发系列博文,通过该系列博文,很多开发者开发出了很多精美的AI健身、线上运动赛事、AI学生体测、美体、康复锻炼等应用场景的AI运动小程序;为了帮助开发者继续深耕AI运动领域市场,今天开始我们将为

    16分钟前
    00
  • 15分钟快速了解 Odoo

    一、引言在企业数字化转型进程中,开源 ERP 系统 Odoo 因模块化设计灵活、功能扩展性强而备受青睐。但新用户在安装和体验 Odoo 时会遭遇难题,像基于 Docker 技术的传统部署,步骤繁琐、镜像拉取不易、配置复杂且管理不便,令许多人

    4分钟前
    00

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信