2017-07-11 28 views
1

在我的應用程序,我需要轉換異步同步(即)一次的setState設置的值,然後我需要在後期調用如何使的setState在陣營同步過程

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, 
    }); 
} 

一旦獲取來自API的數據值設置爲意圖,那麼我需要通過REDX調用fetchIntentReports API調用。

+0

的[的setState(https://facebook.github.io/react/docs/react-component.html#setstate)方法接受一個回調作爲第二個參數。沒有辦法使它真正同步,正如文檔中所解釋的,它更像是一個請求。 – Leandro

回答

2

我強烈建議不要強制進行同步呼叫。幸運的是,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 
     }) 
    ); 
} 
+1

你的工作很好@Dom –

+0

@KARTHISRV真棒!需要幫助請叫我! – Dom

相關問題