在本章中,我们将向您展示如何使用提取处理网络请求。
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
链接:https://www.learnfk.comhttps://www.learnfk.com/react-native/react-native-http.html
来源:LearnFk无涯教程网
import React, { Component } from 'react' import { View, Text } from 'react-native' class HttpExample extends Component { state = { data: '' } componentDidMount = () => { fetch('https://www.learnfk.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
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)