React Native - HTTP



在本章中,我們將向您展示如何使用 fetch 來處理網路請求。

App.js

import React from 'react';
import HttpExample from './http_example.js'

const App = () => {
   return (
      <HttpExample />
   )
}
export default App

使用 Fetch

我們將使用 componentDidMount 生命週期方法,以便元件一經掛載,便可從伺服器載入資料。此函式將向伺服器傳送 GET 請求,返回 JSON 資料,將輸出記錄到控制檯,然後更新我們的狀態。

http_example.js

import React, { Component } from 'react'
import { View, Text } 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>
      )
   }
}
export default HttpExample

輸出

React Native HTTP
廣告