Javascript 状态未在react中更新

Javascript 状态未在react中更新,javascript,reactjs,Javascript,Reactjs,我尝试在输入新员工数据时更新状态。但是推送功能没有将新员工数据插入状态。在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 t

我尝试在输入新员工数据时更新状态。但是推送功能没有将新员工数据插入状态。在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: 'dani@hotmail.com',
                        phone: '0443322118'
                    },
                    {   id: '2',
                        name: 'Dani', 
                        email: 'dani@hotmail.com',
                        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>
        );}
}
//此类将保存表和表单
类EmpContainer扩展了React.Component{
建造师(道具){
超级(道具);
//默认情况下,该州将有以下数据
this.state={参与者:[
{id:'1',
姓名:“丹尼”,
电邮:'dani@hotmail.com',
电话:0443322118
},
{id:'2',
姓名:“丹尼”,
电邮:'dani@hotmail.com',
电话:0443322118
}
]};
}
//这应该会将新的就业数据添加到该州
addPar(emp){
console.log(emp);//显示新员工数据
这个.state.participants.push(emp);
这是我的国家({
参与者:this.state.participants
});}
render(){
返回(
);}
}
我现在将此复制到,并将其制作为CW;这是根据您的代码定制的版本


两个问题:

  • 您不会在React中直接改变state对象。相反,通过
    setState
    提供一个包含新条目的新数组
  • 基于现有状态更新状态时,请使用函数回调版本的
    setState
    ,而不是接受对象的版本,因为状态更新是异步的,可以合并
  • React文档中有更多内容:(不直接修改状态”和“状态更新可能是异步的”部分)

    因此:

    或者使用一个简洁的箭头(我们需要在主体表达式周围使用
    ()
    ,因为我们使用的是对象初始值设定项,
    {
    似乎会启动一个详细的函数主体):

    我现在已经将此复制到并将其制作为CW;这是根据您的代码定制的版本


    两个问题:

  • 您不会直接在React中改变state对象,而是通过
    setState
    提供一个新数组,其中包含新条目
  • 基于现有状态更新状态时,请使用函数回调版本的
    setState
    ,而不是接受对象的版本,因为状态更新是异步的,可以合并
  • React文档中有更多内容:(不直接修改状态”和“状态更新可能是异步的”部分)

    因此:

    或者使用一个简洁的箭头(我们需要在主体表达式周围使用
    ()
    ,因为我们使用的是对象初始值设定项,
    {
    似乎会启动一个详细的函数主体):


    正确使用状态
    +1
    正确使用状态
    +1
    addPar(emp) {
        this.setState(function(state) {
            return {
                participants: [...state.participants, emp]
            }
        });
    }
    
    addPar(emp) {
        this.setState(state => ({
            participants: [...state.participants, emp]
        }));
    }