我需要一些帮助,以便通过GET请求从API提取数据。我只想在控制台中显示数据,但不知道如何在设备上显示数据。有人可以帮我吗?
那是我的代码:
class HomeScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
currentDate: new Date(),
markedDate: moment(new Date()).format("YYYY-MM-DD"),
isLoading: true,
data: ''
};
}
componentDidMount() {
fetch("https://URL/api/schedule?filters[employee_id]=6", {method: "GET"})
.then((response) => response.json())
.then((responseJson) => {
this.setState({...this.state, isLoading:false, data:responseJSON}); //set the state with data
})
.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");
const data = this.state;
return (...
<FlatList
data={this.state.data}
renderItem={({item,index})=>
(
<Text>{item.id}</Text>
)
}
}
keyExtractor={(item)=>item.id.toString()}
/>
)
我想知道然后如何使用它,例如“ {data.id}”(如果我没记错的话)
这是我的.json的一小部分:
"data": [
{
"id": 114,
"employee_id": 6,
"room_id": 17,
"type_of_cleaning": "D",
"date": "2020-10-05"
}, ...
答案 0 :(得分:0)
您应该保存数据,然后甚至使用map()或Flatlist组件对其进行循环
this.state = {
....
data: []
};
componentDidMount() {
fetch("https://URL/api/schedule?filters[employee_id]=6", {method: "GET"})
.then((response) => response.json())
.then((responseJson) => {
this.setState({data: responseJson});
console.log(responseJson);
})
.catch((error) => {
console.error(error);
});
}
Ui
<FlatList
data={this.state.data}
renderItem={({item,index})=>
(
<Text>{item.id}</Text>
)
}
keyExtractor={(item)=>item.id.toString()}
/>
答案 1 :(得分:0)
我认为:
constructor(props) {
super(props);
this.state = {
currentDate: new Date(),
markedDate: moment(new Date()).format("YYYY-MM-DD"),
isLoading: true,
data: [] //should be an array
};
}
componentDidMount() {
fetch("https://URL/api/schedule?filters[employee_id]=6", {method: "GET"})
.then((response) => response.json())
.then((responseJson) => {
this.setState({...this.state, isLoading:false, data:responseJSON}); //set the state with data
})
.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");
const data = this.state.data; //amd you are good from here
}
您只需要setState即可。为了让您的生活更轻松,如果我不提MOBX和Redux可能会使您的生活更轻松,我将被放心