【问题标题】:How to parse Json object in ReactJS如何在 ReactJS 中解析 Json 对象
【发布时间】:2017-07-05 09:24:42
【问题描述】:

我想在 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 变量。你能帮我解决这个问题吗? 提前致谢。

【问题讨论】:

    标签: javascript json reactjs reactjs.net


    【解决方案1】:

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

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

    然后你可以分别从this.state.pageNumberthis.state.count访问pageNumber和count。

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-03-19
        • 2011-07-30
        • 2015-05-18
        • 2013-04-06
        • 2017-09-03
        • 2016-11-16
        • 1970-01-01
        相关资源
        最近更新 更多