首页 > 解决方案 > 如何从 React-Native 中的 API 获取数据?

问题描述

我需要一些帮助来使用 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"
        }, ...

标签: react-nativeapireact-native-android

解决方案


即使使用 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()}
/>

推荐阅读