2017-06-12 110 views
0

兩個相同的ajax調用不同的參數,第二個覆蓋第一個,導致結果不一樣,每次刷新它。第一個setState我已經設置了測試:[],testsHistories:[]在第一個Ajax中,第二個測試集狀態。爲什麼第二個Ajax調用會影響第一個?ReactJS兩個相同的ajax調用不同的參數

class App extends Component { 
    constructor(props){ 
    super(props); 
    this.onFormSubmit = this.onFormSubmit.bind(this); 
    this.state = { tests: [], 
     testsHistories: [], testInfo: []}; 

    $.ajax({ 
     url: "http://localhost:xxxx/api/Testing?sorton=datecompleted&order=asc", 
     success: (data) => { 
     console.log("success"); 
     this.setState({tests: data, testsHistories: data} 
        ); 
     }, 
     error: function(xhr,status,err){ 
      console.log('error'); 
     } 
    }); 

    $.ajax({ 
     url: "http://localhost:xxxx/api/Testing?"+ admissionId, 
    // url: "http://localhost:xxxx/api/Testing?admissionId=5", 
     success: (data) => { 
     console.log("success"); 
     this.setState({testInfo: data}); 
     }, 
     error: function(xhr,status,err){ 
      console.log('error'); 
     } 
    }); 
    } 
+0

是否使用了賦值的'setState'?如果是這樣,您將只能從一個查詢中獲得結果。要將結果「累加」爲單個狀態對象的屬性,請使用[Object#assign](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) – Will

+0

@DarrenSweeney爲什麼你會手動設置狀態並放棄React自動處理狀態更新? – sbking

+0

@sbking你是對的,我讀錯了,我以爲他是從 –

回答

0

你的代碼也應該工作,setState不影響其他state值。

建議和編寫相同的代碼的另一種方式:

不要做API調用的和setStateconstructorconstructor用於初始化變量不更新。

使用componentDidMount生命週期方法,並在那裏做api調用。

作爲每DOC

componentDidMount()後的成分是 安裝被立即調用。需要DOM節點的初始化應該放在這裏。如果 需要從遠程端點加載數據,則這是 實例化網絡請求的好地方。在此方法中設置狀態將會觸發重新渲染。

寫這樣的:

class App extends Component { 
    constructor(props){ 
     super(props); 
     this.onFormSubmit = this.onFormSubmit.bind(this); 
     this.state = { 
      tests: [], 
      testsHistories: [], 
      testInfo: [] 
     }; 
    } 

    componentDidMount(){ 
     $.ajax({ 
      url: "http://localhost:xxxx/api/Testing?sorton=datecompleted&order=asc", 
      success: (data) => { 
       this.setState({tests: data, testsHistories: data}); 
      }, 
      error: function(xhr,status,err){ 
       console.log('error'); 
      } 
     }); 

     $.ajax({ 
      url: "http://localhost:xxxx/api/Testing?"+ admissionId, 
      success: (data) => { 
       this.setState({testInfo: data}); 
      }, 
      error: function(xhr,status,err){ 
       console.log('error'); 
      } 
     }); 
    } 
} 
+0

設置相同的狀態對象我不認爲這是OP問題的答案,但正確的寫作風格肯定 –

+0

正確,不知道他爲什麼面對這個問題。謝謝:)更新了答案 –

0

由於Mayank舒克拉指出,AJAX調用通常在有生命週期方法調用。閱讀更多在https://facebook.github.io/react/docs/state-and-lifecycle.html。至於爲什麼第二個AJAX調用會影響第一個AJAX調用,如果它們影響獨立的狀態片段(看起來如此),它們不應該互相影響,因爲應該合併狀態更新。但是,如果任何一個調用相互影響,我會建議使用回調或承諾來確保狀態更新的順序一致。

相關問題