React-native-http

提供:Dev Guides
移動先:案内検索

React Native-HTTP

この章では、ネットワークリクエストを処理するために fetch を使用する方法を示します。

App.js

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

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

フェッチの使用

コンポーネントがマウントされるとすぐに、 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