【问题标题】:Strange issue with MUI/Material UI multiselect componentMUI/Material UI 多选组件的奇怪问题
【发布时间】:2022-01-01 10:08:30
【问题描述】:

这是我的代码:codesandbox multiselect demo

我需要根据 id 从数组中提取唯一项并将结果数组显示为选项。我正在使用 MUI Select 组件。

当我使用它创建具有不同 id 值的新数组时,它可以工作:

dictinctItems.push(item);

但这由于某种原因不起作用。

dictinctItems.push({ id: item.id, label: item.label });

第二种形式有什么问题?

【问题讨论】:

    标签: reactjs material-ui


    【解决方案1】:

    因为当您执行 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'    
    

    【讨论】:

      猜你喜欢
      • 2016-09-29
      • 1970-01-01
      • 2022-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-28
      • 2020-04-07
      • 1970-01-01
      相关资源
      最近更新 更多