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);
      }
    );
}

相关文章

react 中的高阶组件主要是对于 hooks 之前的类组件来说的,如...
我们上一节了解了组件的更新机制,但是只是停留在表层上,例...
我们上一节了解了 react 的虚拟 dom 的格式,如何把虚拟 dom...
react 本身提供了克隆组件的方法,但是平时开发中可能很少使...
mobx 是一个简单可扩展的状态管理库,中文官网链接。小编在接...
我们在平常的开发中不可避免的会有很多列表渲染逻辑,在 pc ...