简体   繁体   English

如何获取数据 React-native - 获取?

[英]How to get data React-native - fetch?

I am the beginner of react native.我是 react native 的初学者。 I have a problem.我有个问题。 I am trying to get data from an api on react native but i couldn't do this.我正在尝试从反应原生的 api 获取数据,但我无法做到这一点。 There is no compiler error or warning message just emulator gives empty page.没有编译器错误或警告消息,只是模拟器给出了空页。

This is my code:这是我的代码:

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

export default class FetchExample extends React.Component {

  constructor(props){
    super(props);
    this.state ={ isLoading: true}
  }

  componentDidMount(){
    return fetch("https://apidojo-yahoo-finance-v1.p.rapidapi.com/market/get-summary?region=US&lang=en", {
            "method": "GET",
            "headers": {
                "x-rapidapi-host": "apidojo-yahoo-finance-v1.p.rapidapi.com",
                "x-rapidapi-key": "********"
            }
           })
      .then((response) => response.json())
      .then((responseJson) => {

        this.setState({
          isLoading: false,
          dataSource: responseJson.data,
        }, function(){

        });

      })
      .catch((error) =>{
        console.error(error);
      });
  }

  render(){

    if(this.state.isLoading){
      return(
        <View style={{flex: 1, padding: 20}}>
          <ActivityIndicator/>
        </View>
      )
    }

    return(
      <View style={{flex: 1, paddingTop:20}}>
        <FlatList
          data={this.state.dataSource}
          renderItem={({item}) =>  <Text>{item.region}, {item.lang}</Text>}
          keyExtractor={({id}, index) => id}
        />
      </View>
    );
  }
}

Hope for your help.希望得到您的帮助。

You have not declared dataSource in your state .您尚未在state中声明dataSource Declare that variable in your state:在 state 中声明该变量:

constructor(props){
    super(props);
    this.state = { 
        isLoading: true,
        dataSource: [] // Add this line
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM