Javascript 如何在React同步过程中生成setState
在我的应用程序中,我需要将async转换为sync(即,一旦setState设置了值,那么我需要在post调用中从api获取数据Javascript 如何在React同步过程中生成setState,javascript,reactjs,asynchronous,Javascript,Reactjs,Asynchronous,在我的应用程序中,我需要将async转换为sync(即,一旦setState设置了值,那么我需要在post调用中从api获取数据 logChange(val) { this.setState({ fetchIntentReport: { startDate: this.state.fetchIntentReport.startDate, endDate: this.state.fetchIntentReport.endDat
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,
});
}
一旦值设置为intents,那么我需要通过redux调用fetchIntentReports api调用。我强烈建议不要强制执行同步调用。幸运的是,它允许回调函数,因此您可以执行以下操作:
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
})
);
}
该方法接受回调作为第二个参数。没有办法使它真正同步,正如文档中解释的那样,它更像是一个请求。@KARTHISRV真棒!如果你还需要什么,请告诉我!