RN 네트워크 요청(get, post)

2412 단어 RN
간단한 예: 우선 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 (
      
        {this.state.data.map((item, index) => {
          return (
            
              {item.title}
            
          );
        })}
      
    );
  }
}

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 (
      
        
        {this.state.data.loginname}
      
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flexDirection: "row",
    alignItems: "center",
    borderBottomWidth: 1,
    borderColor: "#ddd",
    padding: 10
  },
  avatar: {
    width: 50,
    height: 50,
    borderRadius: 25,
    marginRight: 20
  }
});

좋은 웹페이지 즐겨찾기