【发布时间】:2019-02-13 00:00:59
【问题描述】:
我读过这篇文章:React setState not Updating Immediately
并意识到 setState 是异步的,可能需要第二个参数作为处理新状态的函数。
现在我有一个复选框
class CheckBox extends Component {
constructor() {
super();
this.state = {
isChecked: false,
checkedList: []
};
this.handleChecked = this.handleChecked.bind(this);
}
handleChecked () {
this.setState({isChecked: !this.state.isChecked}, this.props.handler(this.props.txt));
}
render () {
return (
<div>
<input type="checkbox" onChange={this.handleChecked} />
{` ${this.props.txt}`}
</div>
)
}
}
并且正在被另一个应用程序使用
class AppList extends Component {
constructor() {
super();
this.state = {
checked: [],
apps: []
};
this.handleChecked = this.handleChecked.bind(this);
this.handleDeleteKey = this.handleDeleteKey.bind(this);
}
handleChecked(client_id) {
if (!this.state.checked.includes(client_id)) {
let new_apps = this.state.apps;
if (new_apps.includes(client_id)) {
new_apps = new_apps.filter(m => {
return (m !== client_id);
});
} else {
new_apps.push(client_id);
}
console.log('new apps', new_apps);
this.setState({apps: new_apps});
// this.setState({checked: [...checked_key, client_id]});
console.log(this.state);
}
}
render () {
const apps = this.props.apps.map((app) =>
<CheckBox key={app.client_id} txt={app.client_id} handler={this.handleChecked}/>
);
return (
<div>
<h4>Client Key List:</h4>
{this.props.apps.length > 0 ? <ul>{apps}</ul> : <p>No Key</p>}
</div>
);
}
}
所以每次复选框状态发生变化时,我都会更新this.state.apps中的AppList
当我 console.log new_apps 时,一切正常,但 console.log(this.state) 显示状态没有立即更新,这是意料之中的。我需要知道的是,当我需要执行进一步操作(例如注册所有这些选定的字符串或其他内容)时,如何确保更新状态
【问题讨论】:
-
函数
this.setState()是异步的!但作为第二个参数,您可以调用回调,尝试使用this.setState({ apps: new_apps }, _ => console.log(this.state) -
这在反应文档中以及您链接到的问题的答案中有很好的介绍。
-
@meagar 我不明白为什么我的 console.log 没有输出正确的答案,即使我在复选框中使用了回调函数。这就是为什么这篇文章
标签: javascript reactjs