【发布时间】:2021-05-29 20:51:53
【问题描述】:
我在这里被难住了,不知道为什么,因为我之前已经多次过滤反应状态,但这次它做了一些意想不到的事情。
我有一个有输入的功能组件。输入有一个onChange 事件。 on change 事件将e 发送到名为updateSocial 的函数。此函数接受参数,更具体地说,e.target.name 和 e.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