react-native网络请求fetch

前端之家收集整理的这篇文章主要介绍了react-native网络请求fetch前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

学习交流:https://gitee.com/potato512/Learn_ReactNative

react-native学习交流QQ群:806870562


效果


代码示例

import React from 'react';
import {View,Text,Button} from 'react-native';

export default class NetworkRequest extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      //key : value
      message:""
    };
    this.datalist = []
  }

  componentDidMount() {
    console.log("componentDidMount");

     loadDataFetch(this)
  }

  render(){
    return(
      <View style={{marginTop:60}}>
        <Text style={{margin:10,height:40}}>网络请求功能</Text>
        <Button title='请求数据' onPress={() => {loadDataFetch(this)}} />
        <Text style={{margin:10,height:40}}>请求信息:{this.state.message}</Text>
      </View>
    )
  }
}

const loadDataFetch = (that) => {
    fetch('https://www.apiopen.top/satinApi?type=1&page=1').then(
      (response) => response.json()
    ).then(
      (responseJson) => {
        that.datalist = []
        console.log("responseJson:" + responseJson);
        that.datalist = that.datalist.concat(responseJson.data);
        console.log("datalist: " + that.datalist);
        console.log("datalist object: " + that.datalist[0]);
        for (key in that.datalist[0]){
          console.log("datalist object: key = " + key + ",value = " + that.datalist[0][key]);
        }
        that.setState({
          message:that.datalist[0]['text']
        })
      }
    ).catch(
      (error) => {
        console.log("错误:" + error);
      }
    );
}
原文链接:https://www.f2er.com/react/301425.html

猜你在找的React相关文章