简单范例:
首先是get请求:
import React, { Component } from "react";
import { StyleSheet, Text, ScrollView } from "react-native";
export default class FetchGetBasic extends Component {
constructor(props) {
super(props);
this.state = {
data: [] //页面状态
};
}
async componentDidMount() {
let url = "https://cnodejs.org/api/v1/topics?page=1&tab=job&limit=10";
let data = await fetch(url); //获取后台数据
data = await data.json(); //解析获取的数据
this.setState({
//更新页面状态
data: data.data
});
}
render() {
return (
<ScrollView>
{this.state.data.map((item, index) => {
return (
<Text style={styles.list} key={index}>
{item.title}
</Text>
);
})}
</ScrollView>
);
}
}
const styles = StyleSheet.create({
list: {
padding: 20,
borderBottomWidth: 1,
borderColor: "#ddd"
}
});
接下来是post请求:
import React, { Component } from "react";
import { StyleSheet, Text, View, Image } from "react-native";
export default class FetchPostBasic extends Component {
constructor(props) {
super(props);
this.state = {
data: {} //页面状态
};
}
async componentDidMount() {
let url = "https://cnodejs.org/api/v1/accesstoken"; //接口地址
let obj = { accesstoken: "f46b1568-a0c1-4b11-8904-d6c3d07ac026" };
obj = JSON.stringify(obj); //发送JSON字符串给后台
let options = {
//请求头
method: "POST",
headers: {
accept: "application/json",
"Content-Type": "application/json"
},
body: obj
};
let data = await fetch(url, options); //获取后台数据
data = await data.json(); //解析获取的数据
// alert(JSON.stringify(data));
this.setState({
//更新页面状态
data: data
});
}
render() {
return (
<View style={styles.container}>
<Image
style={styles.avatar}
source={{ uri: this.state.data.avatar_url }}
/>
<Text>{this.state.data.loginname}</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flexDirection: "row",
alignItems: "center",
borderBottomWidth: 1,
borderColor: "#ddd",
padding: 10
},
avatar: {
width: 50,
height: 50,
borderRadius: 25,
marginRight: 20
}
});