[英]How to fetch object in object data from API in React-Native
I need to get the data from the object room:{...}, but I'm stuck into just log the whole data from the API in the console.我需要从对象房间获取数据:{...},但我只能在控制台中记录来自 API 的整个数据。 I need some help..............................................................我需要帮助.............................................. …………………………………………………………………………………………………………………………………………
That's my code for now:这是我现在的代码:
class HomeScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
currentDate: new Date(),
markedDate: moment(new Date()).format("YYYY-MM-DD"),
isLoading: true,
room: []
};
}
componentDidMount() {
fetch("https://URL/api/schedule?resolve[]=room", {method: "GET"})
.then((response) => response.json())
.then((responseJson) => {
this.setState({room: responseJson});
console.log(responseJson);
})
.catch((error) => {
console.error(error);
});
}
render() {
const today = this.state.currentDate;
const month = moment(today).format("MMMM");
const date = moment(today).format("D")
const day = moment(today).format("dddd");
return (...)
Here is the JSON:这是JSON:
{
"id": 190,
"employee_id": 6,
"room_id": 28,
"type_of_cleaning": "D",
"date": "2020-10-05",
"room": {
"data": {
"id": 28,
"customer_id": 5,
"room_type_id": 19,
"room_inventory_template_id": 8,
"name": "154",
"floor": 3
}
},
"room-room_type": {
"data": {
"id": 19,
"customer_id": 5,
"name": "room_types_4451C9D4CD"
}
}
}
I need to display the room 'name' and 'floor'.我需要显示房间“名称”和“楼层”。
set initialstate of room to null将房间的初始状态设置为空
this.state = { currentDate: new Date(), markedDate: moment(new Date()).format("YYYY-MM-DD"), isLoading: true, room: null };
let roomName = '' let roomFloor = ' if (this.state.room) { roomName = this.state.room.data.name roomFloor = this.state.room.data.floor }
Your room
state object contain the same data as your JSON.您的room
状态对象包含与 JSON 相同的数据。
You could access the by using name : this.state.room.room.data.name
floor: this.state.room.room.data.floor
您可以使用名称访问: this.state.room.room.data.name
floor: this.state.room.room.data.floor
then you can display it as <Text>{this.state.room.room.data.name}</Text>
and <Text>{this.state.room.room.data.floor}</Text>
然后您可以将其显示为<Text>{this.state.room.room.data.name}</Text>
和<Text>{this.state.room.room.data.floor}</Text>
make sure u have the same structure of data in your state room object when accessing the data or it will cause error确保您在访问数据时在状态室对象中具有相同的数据结构,否则会导致错误
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.