2017-05-04 85 views
1

反應通配符使用的setState

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

我怎樣才能改變這種模式開始假的一切嗎?是否有可能與

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

回答

1

有作爲陣營的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);