Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在React同步过程中生成setState_Javascript_Reactjs_Asynchronous - Fatal编程技术网

Javascript 如何在React同步过程中生成setState

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

在我的应用程序中,我需要将async转换为sync(即,一旦setState设置了值,那么我需要在post调用中从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,
    });
}

一旦值设置为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真棒!如果你还需要什么,请告诉我!