如何在 React Native 中從伺服器載入資料?
要從伺服器載入資料,您可以使用 **fetch API**,它類似於 XMLHttpRequest 或任何其他網路 API。
使用 fetch 向伺服器發出請求非常容易。請檢視以下程式碼:
fetch('https://jsonplaceholder.typicode.com/posts/1') .then((response) => response.json()) .then((responseJson) => console.log(responseJson));
在上面的程式碼中,我們正在獲取 JSON 檔案 https://jsonplaceholder.typicode.com/posts/1 並將資料列印到控制檯。對 fetch() API 的最簡單呼叫接受一個引數,即您要獲取的路徑,它返回一個包含響應的 Promise。
fetch api 返回一個包含 http 響應的 Promise,要從響應中獲取 JSON 內容,我們需要使用 json() 方法。
fetch api 的第二個引數是一個物件,它可以包含方法(GET、POST)、頭資訊、您要釋出的資料等。
這是一個工作示例,它展示瞭如何從伺服器獲取資料並顯示給使用者。
示例:使用 fetch API 獲取資料
資料在開始時初始化為空,如下所示:
state = { data: '' }
關於 componentDidMount() 的詳細資訊
fetch API 在 componentDidMount() 函式內呼叫。componentDidMount() 在元件掛載後立即呼叫,即頁面上所有元素都渲染完成後。
以下是相同程式碼:
componentDidMount = () => { fetch('https://jsonplaceholder.typicode.com/posts/1', { method: 'GET' }) .then((response) => response.json()) .then((responseJson) => { console.log(responseJson); this.setState({ data: responseJson }) }) .catch((error) => { console.error(error); }); }
來自 url 的資料:https://jsonplaceholder.typicode.com/posts/1 如下所示:
{ "userId": 1, "id": 1, "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", "body": "quia et suscipit
suscipit recusandae consequuntur expedita et cum
reprehenderit molestiae ut ut quas totam
nostrum rerum est autem sunt rem eveniet architecto" }
我們感興趣的是顯示 body 內部的文字。
資料變數使用 setState 方法更新,如下所示:
this.setState({ data: responseJson })
因此,現在 this.state.data.body 包含來自伺服器的資料,可以用來顯示給使用者,如下所示:
render() { return ( <View> <Text> {this.state.data.body} </Text> </View> ) }
以下是使用 fetch Api 從伺服器獲取資料的有效程式碼:
import React, { Component } from "react"; import { Text, View } from "react-native"; class HttpExample extends Component { state = { data: '' } componentDidMount = () => { fetch('https://jsonplaceholder.typicode.com/posts/1', { method: 'GET' }) .then((response) => response.json()) .then((responseJson) => { console.log(responseJson); this.setState({ data: responseJson }) }) .catch((error) => { console.error(error); }); } render() { return ( <View> <Text> {this.state.data.body} </Text> </View> ) } } const App = () => { return ( <HttpExample /> ) } export default App
輸出
廣告