我使用计算方式将我的状态设置为
this.setState({ chat-[`${id}`]: some_id })
但问题是我没有id将其设置为false,我可以用setState做正则表达式吗?我想在componentWillMount中将chat- *设置为false。
答案 0 :(得分:0)
这可能适合你:
// newState obj
let newState = {};
// iterate over object keys, finding matching 'chat-*' keys
Object.keys(this.state).forEach((key) => {
if (key.startsWith('chat-')) {
newState[key] = false; // set it to false
}
});
this.setState(newState); // update state
请注意,您的newState会自动合并到旧状态:https://facebook.github.io/react/docs/state-and-lifecycle.html#state-updates-are-merged
答案 1 :(得分:0)
您可以循环更新状态对象,然后将状态设置为
handleClick() {
var obj = {...this.state};
for(var key in obj) {
if(/count-*/g.test(key))
obj[key] = 1;
}
console.log(obj)
this.setState({...obj})
}
段:
class App extends React.Component {
state = {
'count-0': 0,
'count-1': 0
}
handleClick() {
var obj = {...this.state};
for(var key in obj) {
if(/count-*/g.test(key))
obj[key] = 1;
}
console.log(obj)
this.setState({...obj})
}
render() {
return (
<div>
<div>{this.state['count-0']}</div>
<div>{this.state['count-1']}</div>
<button onClick={() => this.handleClick()} >Increase</button>
</div>
)
}
}
ReactDOM.render(<App/>, document.getElementById('app'));
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
&#13;