Reactjs对象数据显示未定义,即使在console.log中显示数据



当我运行这段代码时,它应该呈现

Hello World!

但是它渲染,

Loading...
下面是我的代码:
import React, { Component } from 'react';
class GroupsHomePage extends Component {
constructor() {
super()
this.state={
groupInfo:[]
}
}
componentDidMount(){
let store = JSON.parse(localStorage.getItem('login'))
var url = 'http://127.0.0.1:8000/myapi/groupsdata/'+this.props.groupId+'/?format=json'
fetch(url,{
method:'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Token '+store.token,
},
})
.then(res=>res.json().then(result=>{
this.setState({groupInfo: result})
}))
}
render() {
console.log(this.state.groupInfo)
if(this.state.groupInfo.length){
return (
<div>
<p>Hello World!</p>
</div>
);
}else{
return(
<div className='container'>
<p>Loading...</p>
</div>
)
}

}
}
export default GroupsHomePage;
当我运行代码时,在控制台中显示:

[]

{id: 6, name: "ffff", member: 0, admin: {id: 7, first_name: "test6", last_name: "test6"}}

为什么显示Loading…而不是Hello World!

?

您正在检查是否"groupInfo"具有length的性质。此属性通常与数组或字符串类型相关联。在这种情况下,我认为"groupInfo"是一个对象类型,所以它没有这个length属性。我建议更改条件,并检查是否"groupInfo"具有id属性,例如:

if (this.state.groupInfo.id) {
...
}

另一种方法是将对象转换为数组并检查其长度,如下所示:

if (Object.keys(this.state.groupInfo).length) {
...
}

首先,在构造函数中,默认的groupInfo状态应该是一个空对象groupInfo: {}

检查长度的if条件是这样的

if(Object.keys(this.state.groupInfo).length > 0)

此条件用于与Array

不同的JSON对象键

试试这个。console.log(typeof(this.state.groupInfo))

我认为groupInfo是对象类型。

那么在控制台中,如果你看到上面行对象的输出那么将if条件更改为

if(this.state.groupInfo){

也不要使用
if(this.state.groupInfo.length){

如果您已经将groupInfo定义为[]。因为它会给你true,我认为只有当你在groupInfo数组中有一些数据时,你才需要运行这个if条件。

if(this.state.groupInfo.length !== 0){

是好方法

看起来不错,API可能会欺骗你…

检查length

if(this.state.groupInfo.length){
...
}

确保结构groupInfo是对象的array

最新更新