我有一个名为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"
}
]
};
答案 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)
}
}