RN网络请求(get、post)

简单范例:
首先是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
  }
});

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值