2017-09-05 104 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 –