useEffect React Hook:检测数组中每个对象的属性变化 [英] useEffect React Hook: detecting the change of a property for each object in an array

查看:41
本文介绍了useEffect React Hook:检测数组中每个对象的属性变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

StackOverflow,

StackOverflow,

我有一个关于 React Hooks 的问题,尤其是 useEffect 钩子.我知道 useEffect 钩子的一个用例是捕获某些状态变量的变化.

I'm having a question about React Hooks, more particularly, useEffect hook. I'm aware that one use case of useEffect hook is to capture changes of certain state variables.

假设我们有以下代码:

const MyComponent = () => {
  const [sv, setSv] = useState([
    {
      a: 1,
      b: { c: 'val11', d: 'val12', e: 'val13' }
    },
    {
      a: 8,
      b: { c: 'val21', d: 'val22', e: 'val23' }
    },
    {
      a: 19,
      b: { c: 'val31', d: 'val32', e: 'val33' }
    }
  ]);

  const someCallback = useCallback(() => {
    console.log('change triggered!')
  });

  useEffect(someCallback, [sv]);
}

我们还假设 sv 是一个对象数组,每个对象都有相同的键集,但与这些键关联的值不同.

Let's also assume sv is an array of objects, each of which has the same set of keys, but different values associated with these keys.

如果我想在对 sv 所做的任何更改上执行 someCallback ,它工作得很好,包括嵌套在数组 sv.

It works just fine if I want to execute someCallback on any changes made to sv, including objects nested in each object contained by the array sv.

现在假设只有当数组sv中每个对象的某些属性发生变化时,才需要执行someCallback.例如,我只想监视对 b.cb.d 的更改.我认为可行的方式是:

Now let's assume that there is a need to execute someCallback only when certain properties of each object in the array sv will change. For example, I'll want to only monitor changes to b.c and b.d. The way I thought would work is:

useEffect(someCallback, [sv.map(item => item.b.c), sv.map(item => item.b.d)]);

然而,它根本没有触发.这可能是因为 Array.map 创建一个不引用前一个数组的新数组,但是,我想不出任何其他方法来映射必要的值.

However, it didn't trigger at all. This probably because Array.map creates a new array with no reference to the previous one, however, I can't think of any other way to map the necessary values.

非常感谢任何帮助.

谢谢!

推荐答案

好吧,你肯定不能在 useEffect 依赖中使用 map.而且您使用 map 的方式也不正确.

well, you can surely not use map in the useEffect dependencies. And the way you are using map is not correct either.

我能想到的是,如果你想看的key只有几个,你可以直接用类似的东西

What I can think is that, if the key you want to watch is just a few, you can directly use something like

 useEffect(someCallback, [sv[0].a, sv[1].a, sv[1].b.c]);

这篇关于useEffect React Hook:检测数组中每个对象的属性变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆