簡體   English   中英

在使用 setState 時反應通配符

[英]react wildcard in using setState

我有

this.state = {
   modal_1: true,
   modal_abc: true,
   modal_special: true
}

如何將所有以 modal 開頭的內容更改為 false? 有沒有可能

this.setState({
    `modal_*`: false
})

React 的setState方法或 javascript 的對象字面量中沒有通配符之類的東西。 您可以手動迭代對象鍵並減少它,例如:

const newState = Object.keys(this.state).reduce((result, key) => {
  // conditionally set value of result
  result[key] = key.startsWith('modal_') ? false : this.state[key];
  return result;
}, {});
// and set new state
this.setState(newState);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM