简体   繁体   English

React Native - 未定义不是 object

[英]React Native - Undefined is not an object

I want to get the last item of a json response.我想获得 json 响应的最后一项。

When i do console.log(this.state.details.sessions) it shows me following json object.当我执行console.log(this.state.details.sessions)时,它显示我遵循json object。

[{"login_time": "12-04-2021 20:52:29", "logout_time": ""}, {"login_time": "12-04-2021 20:54:53", "logout_time": "12-04-2021 20:55:13"}] 

But if try to get the length of this item like: Object.keys(this.state.details.sessions).length i get this following error:但是,如果尝试获取此项目的长度,例如: Object.keys(this.state.details.sessions).length我收到以下错误:

undefined is not an object (evaluating 'Object.keys(data.sessions)') undefined 不是 object(评估“Object.keys(data.sessions)”)

const {number} = this.props.route.params;
database().ref('/numbers/'+number.replace('+', ''))
          .on('value', (snapshot) => {
            const userObj = snapshot.val();
            this.setState({
                details: userObj
          })
});

console.log(Object.keys(this.state.details.sessions).length);

What can be the problem?可能是什么问题?

in the very first this.state.details.sessions is undefined , you cannot use Object.keys on that在第一个this.state.details.sessionsundefined的,你不能使用Object.keys

after you set data into that在您将数据设置为之后

this.setState({
  details: userObj,
});

this.state.details.sessions is actually an array this.state.details.sessions实际上是一个数组

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM