简体   繁体   English

Reactjs object 数据即使在 console.log 中显示数据后仍显示未定义

[英]Reactjs object data showing undefined even after showing data in console.log

When i run this code, it should render当我运行此代码时,它应该呈现

Hello World!

But it render,但它呈现,

Loading...

Here is my code:这是我的代码:

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;

When i run the code, in console it shows:当我运行代码时,在控制台中显示:

[ ] [ ]

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

why it shows Loading... instead of Hello World!为什么它显示Loading...而不是Hello World! ? ?

You are checking if "groupInfo" has the length property.您正在检查“groupInfo”是否具有length属性。 This property is usually associated to an array or a string type.此属性通常与数组或字符串类型相关联。 In this case, I think "groupInfo" is an object type, so it doesn't have this length property.在这种情况下,我认为“groupInfo”是一个 object 类型,所以它没有这个length属性。 I suggest to change the condition and check if "groupInfo" has the id property for example:我建议更改条件并检查“groupInfo”是否具有id属性,例如:

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

Another approach could be to convert that object in an array and check for its length, like this:另一种方法是将 object 转换为数组并检查其长度,如下所示:

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

So firstly your default groupInfo state should be an empty object in constructor like this groupInfo:{}因此,首先您的默认 groupInfo state 在构造函数中应该是一个空的 object,如下所示:{}

And to check length your 'if' condition would be this并检查长度你的“如果”条件是这样的

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

This condition is used for JSON object keys different from Array此条件用于与 Array 不同的 JSON object 键

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

I think groupInfo is of object type.我认为 groupInfo 属于 object 类型。

So in console if you see the output of above line object then change the if condition to因此,在控制台中,如果您看到上述 object 行的 output 则将 if 条件更改为

        if(this.state.groupInfo){

Also you should not use 你也不应该使用
if(this.state.groupInfo.length !== 0){

if you have groupInfo already defined as [].如果您已将 groupInfo 定义为 []。 Because it will give you true and i think you only want to run this if condition when you have some data in groupInfo array.因为它会给你真实的,我认为你只想在 groupInfo 数组中有一些数据时运行这个 if 条件。

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

Is good way是好办法

Looks ok, the API might lie to you...看起来不错,API 可能会骗你……

Before you check length在检查length之前

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

make sure the structure groupInfo is array of objects.确保结构groupInfo是对象array

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么即使在等待所有承诺解决之后,最终的 console.log 也没有显示整个数据? - Why isnt the final console.log showing the whole data even after waiting for all promises to resolve? Console.log 只显示对象而不是数据 - Console.log only showing object instead of data console.log上显示什么类型的数据? - What type of data is showing on console.log? 即使对象上的console.log显示属性值,对象的属性也未定义 - Property of object is undefined, even though console.log on object is showing the property value 尽管在 console.log 中显示,但 React Array 未在 .map 中显示数据 - React Array not showing data in .map despite showing in console.log Object 属性以点表示法调用,显示 console.log 'undefined' - Object property called with dot notation showing console.log 'undefined' 为什么我的console.log首先显示&#39;未定义&#39;然后显示所需的数字,即使在我在2秒的settimeout之后记录它{REACT} - Why my console.log is showing 'Undefined' first And Then Display The required number even after i log it after a settimeout of 2 sec {REACT} 与 console.log / console.table 以不同顺序显示的数据 - Data showing in different order with console.log / console.table falsey var在console.log中显示未定义 - falsey var showing undefined in console.log 注销再登录后数据不显示 - reactjs - Data not showing after log out and then log in - reactjs
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM