如何在 ReactJS 中解析 Json 对象

How to parse Json object in ReactJS

我想在 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 });

它将正常工作并且可以遍历员工列表。但无法访问页码和计数变量。你能帮我解决这个问题吗? 提前致谢。

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

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

然后您可以访问页码并分别从this.state.pageNumberthis.state.count开始计数。

在 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);

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