0

我想通过 reactJS 中的 JSON 列表进行解析。这是我正在使用的模型

public class ModelEmployee
{
    public List<Employeelist> Employees { get; set; }
    public int count { get; set; }
    public int Pagenumber { get; set; }
}
public class Employeelist
{
    public int EmployeeID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Phone { get; set; }
    public int RoleId { get; set; }
    public string RoleName { get; set; }
    public List<string> Roles { get; set; }
}

我的控制器是

 public ActionResult Index(int pageNum = 1)
    {
        ModelEmployee model = new ModelEmployee();   
            model = new ModelEmployee();
            model.Employees = FetchAllDevices(pageNum, 10);
            model.count = (int)Math.Ceiling((float)_empService.TotalCount() / _pageSize);
            model.Pagenumber = pageNum;
            return Json(model,JsonRequestBehavior.AllowGet);            
    }

这就是我在 ReactJS 代码中尝试提取每个值的方法

 componentWillMount: function(){  

    var xhr = new XMLHttpRequest();  
    xhr.open('get', this.props.url, true);  
    xhr.onload = function () {  
        var response = JSON.parse(xhr.responseText);   
        this.setState({ result: response });

    }.bind(this);  
    xhr.send();  
},  
render: function(){  
    var rows = [];  
    this.state.result.Employees.forEach(function (item) {  
        rows.push(<EmployeeRow  key={item.EmployeeID} item={item }/>);  
});

它不工作。但是当我用这个改变 setState 时,

this.setState({ result: response.Employees });

它可以正常工作,并且可以通过员工列表。但无法访问 pagenumber 和 count 变量。你能帮我解决这个问题吗?提前致谢。

4

2 回答 2

0

为什么不将计数和页码也存储在状态中?

this.setState({ 
  employees: response.Employees,
  count: response.count,
  pageNumber: response.PageNumber
});

然后您可以分别访问 pageNumber 和 count fromthis.state.pageNumberthis.state.count

于 2017-07-05T09:40:04.273 回答
0

在 XHR 的 onLoad 回调中,您应该确保检查 readyState,以确保响应已完成:

xhr.onload = function () {
    if (xhr.readyState === xhr.DONE) {
        if (xhr.status === 200) { // optionally check the status
            var response = JSON.parse(xhr.responseText);   
            this.setState({ result: response });
        }
    }

}.bind(this);

这可以确保您正在阅读完整的响应。试试这个,看看这是否解决了问题

于 2017-07-05T10:02:13.193 回答