在本章中,我们将向您展示如何使用提取处理网络请求。
App.js
import React from react; import HttpExample from ./http_example.jsconst App = () => { return ( <HttpExample /> ) } export default App
使用Fetch
一旦安装了组件,我们将使用 componentDidMount 生命周期方法从服务器加载数据,此函数将向服务器发送GET请求,返回JSON数据,将输出记录到控制台并更新我们的状态。
http_example.js
import React, { Component } from react import { View, Text } from react-nativeclass HttpExample extends Component { state = { data: } componentDidMount = () => { fetch(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
