KAR*_*SRV 2 javascript asynchronous reactjs
在我的应用程序中,我需要将异步转换为同步(即)一旦 setState 设置了值,那么我需要在调用后从 api 获取数据
logChange(val) {
this.setState({
fetchIntentReport: {
startDate: this.state.fetchIntentReport.startDate,
endDate: this.state.fetchIntentReport.endDate,
intents: val.split(','),
},
});
this.props.fetchIntentReports({
startDate: this.state.fetchIntentReport.startDate,
endDate: this.state.fetchIntentReport.endDate,
intents: this.state.fetchIntentReport.intents,
});
}
Run Code Online (Sandbox Code Playgroud)
一旦值设置为意图,那么我需要通过 redux 调用 fetchIntentReports api 调用。
我强烈建议不要强制同步调用。幸运的是,setState允许回调函数,因此您可以执行以下操作:
logChange(val) {
var startDate = this.state.fetchIntentReport.startDate;
var endDate = this.state.fetchIntentReport.endDate;
var intents = val.split(',');
this.setState({
fetchIntentReport: {
startDate,
endDate,
intents
}
}, () => {
// if you need the updated state value, use this.state in this callback
// note: make sure you use arrow function to maintain "this" context
this.props.fetchIntentReports({
startDate,
endDate,
intents
})
);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7406 次 |
| 最近记录: |