- React Native 教程
- React Native - 首页
- 核心概念
- React Native - 概述
- React Native - 环境设置
- React Native - 应用
- React Native - 状态
- React Native - 属性
- React Native - 样式
- React Native - Flexbox
- React Native - ListView
- React Native - 文本输入
- React Native - ScrollView
- React Native - 图像
- React Native - HTTP
- React Native - 按钮
- React Native - 动画
- React Native - 调试
- React Native - 路由器
- React Native - 运行 iOS
- React Native - 运行 Android
- 组件和 API
- React Native - View
- React Native - WebView
- React Native - Modal
- React Native - ActivityIndicator
- React Native - Picker
- React Native - 状态栏
- React Native - Switch
- React Native - Text
- React Native - Alert
- React Native - 地理定位
- React Native - AsyncStorage
- React Native 有用资料
- React Native - 快速指南
- React Native - 有用资料
- React Native - 讨论
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
输出
广告