我的代码中有一个名为CarValues的字典,其中包含以下数据: CarValues是在该州初始化的字典。
dictionary: CarValues
key ==> string
Value ==> Array
key => Honda, Value => white, yellow, red, orange
key => Toyota, Value => white, yellow, green, black
Key => Volkswagen Value => 123, 456, 343
我想完全从CarValues中删除本田及其价值。虽然,我看到几个类似的问题,但我找不到这个问题的最佳解决方案。
How can I remove an attribute from a Reactjs component's state object
答案 0 :(得分:1)
这可以解决您的问题
yourMethod(key) {
const copyCarValues= {...this.state.CarValues}
delete copyCarValues[key]
this.setState({
CarValues: copyCarValues,
})
}
答案 1 :(得分:0)
我相信为了在不改变状态的情况下真正做到这一点,你需要像这样重新创建整个状态。
class Test extends React.Component {
state = {
thingToDelete: {},
otherStuff: {}
};
deleteThingToDelete = () => {
const {thingToDelete, ...state} = this.state;
this.setState({state});
}
}
使用扩展运算符,我们实现了浅层克隆,因此要小心谨慎。另一种选择是使用Object.assign,但这也只提供浅层克隆,但你将获得更好的浏览器支持。
答案 2 :(得分:0)
最简单的方法是:
const carValues = Object.assign({}, this.state.carValues)
delete carValues[key]
this.setState({ carValues })
答案 3 :(得分:0)
您可以使用Underscore.js或Lodash http://underscorejs.org/#omit
_.omit(copyCarValues, 'Honda');
答案 4 :(得分:0)
全局第一个初始化数组
var dict = []
将对象添加到字典中
dict.push(
{ key: "One",value: false},
{ key: "Two",value: false},
{ key: "Three",value: false});
Output :
[0: {key: "One", value: false},
1: {key: "Two", value: false},
2: {key: "Three", value: false}]
从字典更新对象
Object.keys(dict).map((index) => {
if (index == 1){
dict[index].value = true
}
});
Output :
[0: {key: "One", value: false},
1: {key: "Two", value: true},
2: {key: "Three", value: false}]
从字典中删除对象
Object.keys(dict).map((index) => {
if (index == 2){
dict.splice(index)
}
});
Output :
[0: {key: "One", value: false},
1: {key: "Two", value: true}]
答案 5 :(得分:0)
可能到达这里有点晚了,但这里有一种使用钩子来做到这一点的方法,而无需实际改变之前的状态。
const sampleItems = {
'key1': { id: 1, name: 'test'},
'key2': { id: 2, name: 'test2'},
}
const Test = props => {
const [items, setItems] = useState(sampleItems);
deleteItemFromStateObject = itemKey => {
setItems(({[itemKey]: toDelete, ...rest}) => rest);
}
}