Javascript 具有反应状态的筛选器不筛选值
我在这里被难住了,不知道为什么,因为我已经多次过滤了react状态,但这次它做了一些意想不到的事情 我有一个有输入的功能组件。输入有一个Javascript 具有反应状态的筛选器不筛选值,javascript,reactjs,use-state,Javascript,Reactjs,Use State,我在这里被难住了,不知道为什么,因为我已经多次过滤了react状态,但这次它做了一些意想不到的事情 我有一个有输入的功能组件。输入有一个onChange事件。更改时事件将e发送到名为updateSocial的函数。此函数获取参数e,更具体地说,e.target.name和e.target.value,并创建一个对象以存储在状态中{inputType:e.target.name,value:e.target.value} 状态,bandSocials是这些对象的数组。。。如果用户编辑该字段,函数应
onChange
事件。更改时事件将e
发送到名为updateSocial
的函数。此函数获取参数e,更具体地说,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
事件时,它都会添加另一个对象,并且不会过滤掉旧对象。与修改数组的push
不同,filter
创建一个新数组并返回它
let filteredArray = socialsArray.filter( ... )
与修改数组的
push
不同,filter
创建一个新数组并返回它
let filteredArray = socialsArray.filter( ... )