繁体   English   中英

即使使用删除运算符后,对象属性也不会被删除

[英]object property is not getting deleted even after using delete operator

我有一个对象数组。 我想从中删除一个名为id键。 我使用以下代码将其从对象中删除。

this.state.result.forEach(item => delete item.id);

但是,id 并没有从中删除。 我不确定为什么我的代码有什么问题。 我尝试使用上述逻辑从同一对象中删除其他几个键,并且效果很好。 我面临的唯一问题是id

我认为这个对象属性是不可配置的。 如果是这样,那么我们如何删除它。

有人可以帮我解决这个问题。 提前致谢。

也许idnon-configurable ,那么你不能删除它。 请参阅此链接 请注意,仅在严格模式下才会抛出TypeError

在 React.js 中,你永远不应该尝试直接改变状态。 从官方文档中查看这篇文章。 您必须使用 setState() 来实现结果。 id 没有被删除,因为没有重新渲染。

从文档中,

不要直接修改状态

// Wrong
this.state.comment = 'Hello';

相反,使用 setState():

// Correct
this.setState({comment: 'Hello'});

在 React 中,你不能直接更新state 你总是必须使用setState方法来做到这一点。

所以试试这个。

this.setState({
 result: this.state.result.map(item => {
  let tmpItem = {...item};
  delete tmpItem.id;
  return {...tmpItem}; 
 })
});

谢谢!

**

如果您使用的是 react,那么您应该始终使用 setState 来更改状态。

**

解释@Prabu答案

    this.setState({ // calling setState for updating the state
       result: this.state.result.map(item => {
           let tmpItem = {...item};// storing all the value here in tmpItem
           delete tmpItem.id; // deleting the key
           return {...tmpItem}; // returning here
       })
    }, ()=> {
        // for immediatly accessing the state you can use callback
    });

在计算下一个状态时,您永远不应该依赖state :s 值,因为它可能会在幕后由 React 异步更新。

另外,尽量避免delete因为它是性能杀手。

所以试试这个:

this.setState((state, props) => ({
  result: state.result.map(({id, ...propsToKeep}) => propsToKeep)
}));

或者如果您必须使用delete

this.setState((state, props) => ({
  result: state.result.map(res => { 
    delete res.id; 
    return res; 
  });
}));

暂无
暂无

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

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