【问题标题】:filter with react state not filtering values具有反应状态的过滤器不过滤值
【发布时间】:2021-05-29 20:51:53
【问题描述】:

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

我有一个有输入的功能组件。输入有一个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 事件时,都会添加另一个对象,不会过滤掉旧对象。

【问题讨论】:

    标签: javascript reactjs use-state


    【解决方案1】:

    与修改数组的push 不同,filter 创建一个新数组并将其返回。

    let filteredArray = socialsArray.filter( ... )
    

    【讨论】:

      猜你喜欢
      • 2019-05-18
      • 2023-03-20
      • 2020-02-02
      • 2021-06-03
      • 1970-01-01
      • 2017-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多