因为当您执行 dictinctItems.push(item); 时,您将同一对象的引用推送到列表中,而当您执行 dictinctItems.push({ id: item.id, label: item.label }); 时,您每次都推送一个新对象。
在您的组件中,每次选择一个新值时,您都会更改 handleChange 中的状态,这将触发重新渲染,此重新渲染将再次在组件顶部运行您的 getDistinctItemsById 函数,并且执行 dictinctItems.push({ id: item.id, label: item.label }); 时返回一个新列表。
如果你使用 useMemo 可以解决这个问题
const dictinctItems = getDistinctItemsById(listData)
到
const dictinctItems = useMemo(() =>getDistinctItemsById(listData), [])
无论您使用dictinctItems.push(item); 还是dictinctItems.push({ id: item.id, label: item.label });,每次重新渲染都将始终拥有相同的对象
只是为了更了解在 javascript 中复制引用和值
看看下面这个例子
let stringValue = 'Hi';
const objValue = {id: "1", label: 'P1'};
// for primitive value, it copy gets pushed to array
const myArray = [];
myArray.push(stringValue); // push copy of 'Hi' here
stringValue = 'Hi how are you'; // change 'Hi' to 'Hi how are you'
console.log(myArray[0]); // myArray still contains 'Hi'
// for objects, its reference gets pushed
const newArray = [];
newArray.push(objValue); // puts object reference into the array
objValue.id = "2"; // change 'id' property
console.log(newArray[0].id); // here id will be changed to '2'