过滤反应状态而不是过滤值

filter with react state not filtering values

我在这里被难住了,不知道为什么,因为我之前已经多次过滤反应状态,但这次它做了一些意想不到的事情。

我有一个具有输入的功能组件。输入有一个 onChange 事件。 on change 事件将 e 发送到名为 updateSocial 的函数。此函数采用参数,更具体地说,e.target.namee.target.value,并创建一个对象以存储在状态中。 {inputType: e.target.name, value: e.target.value}.

状态,bandSocials是这些对象的数组...如果用户编辑字段,函数应该过滤掉旧值,并用新值替换它。

这是我的代码:

  const updateSocial = (e) => {
    //Turn the bandSocials state into a new array so that I don't change the existing state yet.
    let socialsArray = Array.from(bandSocials)

    //Define the input type and the value.
    let inputType = e.target.name
    let value = e.target.value

    //Filter out the old value- This is where it is not working.
    socialsArray.filter((s) => s.inputType !== inputType);

    //Add in the new value
    socialsArray.push({inputType, value})

    //Replace the bandSocails with the new array.
    setSocials((band) => {
      return {
        ...band,
        bandSocials : socialsArray,
      };
    });
  };

每次调用onChange事件时,都会添加另一个对象,不会过滤掉旧对象。

与修改数组的 push 不同,filter 创建一个新数组并 returns 它。

let filteredArray = socialsArray.filter( ... )