在状态中设置X后,React - this.state.X未定义

时间:2018-04-11 08:21:16

标签: reactjs state

我试图在状态中存储用户数组。 在数组中设置用户后,this.state.users将返回undefined。

第一次记录:

(18) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]

第二次记录:

undefined

功能

$.ajax(
      {
        url:url,
        cache:false,
        success: function(data){
          console.log(data.employees);
          this.setState({users:data.employees, employeeId: data.Id,firstName:data.firstName,lastName:data.lastName,email: data.email, trialPeriod: data.trialPeriod,
            dayOfStart: data.dayOfStart, endOfcontract: data.endOfcontract,employmentType:data.employmentType, salary: data.salary, phoneNumber: data.phoneNumber,employerId: data.employerId});
          console.log(this.state.users);
        }.bind(this),
        error: function(xhr, status, err){
            console.log(err);
        }
      });

这个

1 个答案:

答案 0 :(得分:0)

您必须使用setState回调函数。

$.ajax(
      {
        url:url,
        cache:false,
        success: function(data){
          console.log(data.employees);
          this.setState({users:data.employees, employeeId: data.Id,firstName:data.firstName,lastName:data.lastName,email: data.email, trialPeriod: data.trialPeriod,
            dayOfStart: data.dayOfStart, endOfcontract: data.endOfcontract,employmentType:data.employmentType, salary: data.salary, phoneNumber: data.phoneNumber,employerId: data.employerId},
            ()=>{
              console.log(this.state.users);
            });
        }.bind(this),
        error: function(xhr, status, err){
            console.log(err);
        }
      });