如何在React JS中将数组值设置为状态

时间:2018-05-31 11:11:50

标签: reactjs

我有一个名为resultArray的对象数组,如

[
  {
    "name": "Morgan",
    "category": "on",
    "dept": "A1"
  },
  {
    "name": "Lewis",
    "category": "on",
    "dept": "A2"
  },
  {
    "name": "Ivan",
    "category": "off",
    "dept": "A3"
  }
]

在我的API结果中。如何将它们设置为state以获得结果

this.state = { 
  person: [
    {
      "name": "Morgan",
      "category": "on"
    },
    {
      "name": "Lewis",
      "category": "on"
    },
    {
      "name": "Ivan",
      "category": "off"
    }
  ]
};

2 个答案:

答案 0 :(得分:0)

最初,在person对象中声明state密钥[]这样的值

constructor(props){
  this.state.person = [];
}

并更新列表使用setState,如

this.setState({person : resultArray });

答案 1 :(得分:0)

如果要设置默认数据,请使用constructor,或者如果要进行ajax调用,请使用componentDidUpdate。请参阅下面的示例代码。

class Mycomponent extends React.Component{
    constructor(props){
        super(props)
        this.state = {
          person: [
            {name:"Morgan", category:"on"},  
            {name:"Lewis", category:"on"},
            {name:"Ivan", category:"off"}          
          ]
        }
    }
    componentDidUpdate(){
        // make some ajax call to get data
        // now set state like
        data = {
          person: [
            {name:"Morgan", category:"on"},  
            {name:"Lewis", category:"on"},
            {name:"Ivan", category:"off"}          
          ]x
        }
        this.setstate(data)
    }
}