簡體   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