2017-09-05 88 views
0

我試圖更新狀態時,新的員工數據輸入。但推功能沒有插入新的員工數據的狀態。在addpar函數我已經設置了console.log和它結果表明,數據是有,但它不能推陳述狀態沒有反應

// this class will hold the table and the form 

class EmpContainer extends React.Component{ 
    constructor(props) { 
     super(props); 
    // the state will have the following data by default 
     this.state = {participants : [ 
        {  id: '1', 
         name: 'Dani', 
         email: '[email protected]', 
         phone: '0443322118' 
        }, 
        {  id: '2', 
         name: 'Dani', 
         email: '[email protected]', 
         phone: '0443322118' 
        } 
       ]}; 
    } 

    // this supposed to add the new employed data to the state 
    addPar (emp){ 
    console.log(emp); // this shows the new employee data 

    this.state.participants.push(emp); 
     this.setState({ 
     participants: this.state.participants 
     });} 
render() { 
     return (
      <div> 
      <AddNewParticipant addNew={this.addPar}/> 
      </div> 
     );} 
} 

回答

2

現在我已經複製這an answer to the dupetarget並提出這樣的CW;這裏是適合你的代碼的版本。


兩個問題:

  1. 不要直接在陣營變異狀態對象。相反,請通過setState提供一個新的陣列及其中的新條目。
  2. 根據現有狀態更新狀態時,請使用函數回調版本setState,而不是接受對象的版本,因爲狀態更新是異步的並可能會合並。

更多有關React文檔:Using State Correctly(「不直接修改狀態」和「狀態更新可能是異步」部分)。

所以:

addPar(emp) { 
    this.setState(function(state) { 
     return { 
      participants: [...state.participants, emp] 
     } 
    }); 
} 

或者用簡潔的箭頭(我們需要在身體周圍表達(),因爲我們使用的對象初始化,以及{否則似乎開始一個詳細的函數體):

addPar(emp) { 
    this.setState(state => ({ 
     participants: [...state.participants, emp] 
    })); 
} 
+0

'使用狀態正確'+1 –