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

标签 javascript react-native fetch

我是 React Native 的初学者。我有个问题。 我正在尝试从 React Native 上的 api 获取数据,但我无法做到这一点。没有编译器错误或警告消息,只是模拟器给出空页。

这是我的代码:

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

希望得到您的帮助。

最佳答案

您尚未在状态中声明dataSource。在您所在的州声明该变量:

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

关于javascript - 如何获取数据 React-native - fetch?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58518281/

相关文章:

javascript - 将 HTML 分页,拆分长段落

javascript - 如何通过onClick()函数保留highchart折线图 - php mysql

android - 使用 Flatlist 单击播放按钮即可全屏(横向)播放视频

javascript - 为什么我的提取请求被多次发送?

javascript - 无法在 Chrome 开发工具控制台中查询模式对话框的元素

javascript - 删除prototypejs中的类名

javascript - React Native - navigation.navigate 不是一个函数

scope - TouchableHighLight onPress 在 react native 的 map 函数内

node.js - 等待很长时间时,Fetch 给出空响应

mercurial - 我们如何自定义 fetch 扩展使用的默认提交消息?