简体   繁体   English

移除 React State 中的嵌套对象

[英]Remove nested object in React State

In React I have some filters in a state:在 React 中,我有一些过滤器处于某种状态:

this.state {
   filters: [countries: {parameterName: 'country', value: 'England'}, 
                        {parameterName: 'country', value: 'Greenland'}]
}

In an onClick-Handler function I receive one of these objects:在 onClick-Handler 函数中,我收到以下对象之一:

removeFilter(filter) {     
        console.log('remove->', filter);
        // outputs: {value: 'England', parameterName: 'country'} 
}

Is there a way to remove that object from my state using setState?有没有办法使用 setState 从我的状态中删除该对象? I currently try using 'find' to get the object inside the state itself but I'm not sure how to remove it:我目前尝试使用“查找”来获取状态本身的对象,但我不确定如何删除它:

let found ? this.state.filters[filter.parameterName].find(element => element.value === filter.value))

Looks like this is a react state management question, so you want to avoid mutation, by that I mean that you don't want to manipulate the original array object.看起来这是一个反应状态管理问题,所以你想避免突变,我的意思是你不想操纵原始数组对象。 So you want to create a new array excluding the one that you want to remove.因此,您要创建一个新数组,不包括要删除的数组。 Like:喜欢:

const newFilter = countryFilter.filter(f => f.value !== filter.value); const newFilter = countryFilter.filter(f => f.value !== filter.value);

then you want to keep constructing the new state object, and place this array where it belongs on the state object.然后你想继续构造新的状态对象,并将这个数组放在它所属的状态对象上。

I think the state object you pasted in your question is not correct, so I am not trying to guess the correct structure of it.我认为您粘贴在问题中的状态对象不正确,所以我不想猜测它的正确结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM