React useEffect():比较两个对象数组是否相等的最有效方法 [英] React useEffect() : Most efficient way to compare if two arrays of objects are equal

查看:81
本文介绍了React useEffect():比较两个对象数组是否相等的最有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个useEffect(),当对象数组更改时应触发.

I have a useEffect() that should trigger when an array of objects changes.

  useEffect(() => {
    setNotesToRender(props.notes)
  }, [props.notes]);

useEffect依赖项无法比较对象数组,因此上面示例中的useEffect()触发的次数比需要的要多.我只希望在数组 differ 时触发useEffect().

The useEffect dependency cannot compare arrays of objects, so the useEffect() in the example above triggers more often than needed. I only wish to trigger the useEffect() when the arrays differ.

应该触发更新的数组的示例

An example of arrays that should trigger update

array1 = [{id:1,title:'one'},{id:2,title:'two'},{id:3,title:'three'}]
array2 = [{id:1,title:'one'},{id:2,title:'two'},{id:3,title:'four'}]

到目前为止,我测试过的东西是:

Things I have tested so far are:

  1. props.notes.length->可行,但不可靠-出于明显的原因:)
  2. ... props.notes->如果数组为空将无法正常工作-可能会导致严重的性能问题?

比较两个对象数组的最有效方法是什么?数组可能包含1000多个对象.

What is the most efficient way to compare two arrays of objects? The arrays may contain over 1000 objects.

亲切的问候/K

更新我需要过滤掉某些注释"后来使用文本搜索,这就是为什么我使用React状态.这在我的示例代码中未显示.

UPDATE I need to filter out certain "notes" later using a text search, that's why I am using a React state. This is not shown in my example code.

推荐答案

最有效的方法是什么

What is the most efficient way

最有效的方法可能是针对此特定形状的数据进行自定义比较.您可以使用 JSON.stringify 或其他一些通用比较函数,但是出于明显的原因,它可能不是最有效的.

The most efficient way is likely a custom compare for this particular shape of data. You could use JSON.stringify or some other generic comparing function, but it's not likely to be the most efficient for obvious reasons.

因此在您的示例中,一个简单的比较功能可能类似于->

So in your example a simple compare function might look like ->

const array1 = [{id:1,title:'one'},{id:2,title:'two'},{id:3,title:'three'}];
const array2 = [{id:1,title:'one'},{id:2,title:'two'},{id:3,title:'four'}];

const arrayIsEqual = (a1, a2) => 
  a1 === a2 ||
  a1.length === a2.length &&
  a1.every((f,i) => 
    f.id === a2[i].id &&
    f.title === a2[i].title
  )
  
  
//tests
const a1clone = [...array1];

//different arrays not equal
console.log(arrayIsEqual(array1, array2)); //false

//different arrays equal
console.log(arrayIsEqual(array1, a1clone)); //true

//different arrays same values, but different order
a1clone.reverse();
console.log(arrayIsEqual(array1, a1clone)); //false

//same arrays, fastest check
console.log(arrayIsEqual(array1, array1)); //true

这篇关于React useEffect():比较两个对象数组是否相等的最有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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