2017-05-04 86 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);