无法访问JSON属性

问题描述 投票:0回答:1

我一直在和这个看似简单的问题争吵好两个小时..请教育我。我只是不明白我做错了什么。

我有一个PHP脚本,我从一个带有$ .get函数的react组件调用,如下所示:

this.serverRequest = $.get("php/get_house.php", {"id":this.props.houseId}, function(data){
    this.setState({house: data, loading: false});
}.bind(this)); 

然后我将this.state.house中的数据传递给另一个组件:

<ShowHouse house={this.state.house} />

在ShowHouse组件中,我记录数据:

console.log(this.props.house);
console.log(this.props.house[0]);

第一个返回chrome控制台显示为[{...}]的内容,数据位于0:nth位置,第二个返回您期望的内容 - 只是正常JSON格式的数据,如下面的块中所示。

如果我只是打开带有id的PHP脚本,我会在页面上打印我的JSON,比如..php?id = 1

[{"heading":"Kuin uusi","id":"1","city":"Helsinki"}]  

我如何访问这些数据?如果我只是尝试访问它,我会收到错误“无法读取未定义的属性'标题”

console.log(this.props.house[0].heading).
javascript php jquery json reactjs
1个回答
0
投票

您可以使用数组语法

this.props.house[0]["heading"]
© www.soinside.com 2019 - 2024. All rights reserved.