如何从React Native中存储在GitHub的JSON文件中加载数据?

时间:2018-01-17 11:50:53

标签: json github react-native fetch

我有以下JSON file in my GitHub并希望加载它:

{"Cat": [
    {"key": "a", "title": "Bangladesh", "image": "https://raw.githubusercontent.com/mudassir21/server/master/img/bangladesh.jpg"},
    {"key": "b", "title": "Sports", "image": "https://raw.githubusercontent.com/mudassir21/server/master/img/sports.jpg"},
    {"key": "c", "title": "Politics", "image": "https://raw.githubusercontent.com/mudassir21/server/master/img/politics.jpg"},
    {"key": "d", "title": "Entertainment", "image": "https://raw.githubusercontent.com/mudassir21/server/master/img/entertainment.png"},
    {"key": "e", "title": "Economics", "image": "https://raw.githubusercontent.com/mudassir21/server/master/img/economics.jpg"},
    {"key": "f", "title": "Technology", "image": "https://raw.githubusercontent.com/mudassir21/server/master/img/technology.jpg"},
    {"key": "g", "title": "Others", "image": "https://raw.githubusercontent.com/mudassir21/server/master/img/m.jpg"}
]}

我尝试使用以下代码来获取它:

getMoviesFromApiAsync() {
  return fetch('https://raw.githubusercontent.com/mudassir21/server/master/newsCategory.json')
    .then((response) => response.json())
    .then((responseJson) => {
      return responseJson.Cat;
    })
    .catch((error) => {
      console.error(error);
    });
}
<FlatList horizontal= {true}
   data={this.getMoviesFromApiAsync()}
   renderItem={({item}) => (                
      <TouchableOpacity
        style={styles.catOption}
        onPress = { ()=> this.setState({ name: item.title })}
      >
         <Image
            style={styles.imgButton}
            source={{uri: item.image}}
          />
          <Text style={styles.buttonText}>{item.title}</Text>
       </TouchableOpacity>
       )
  }
/>

但是,没有从JSON文件加载数据。问题是什么?

2 个答案:

答案 0 :(得分:1)

在呈现列表时触发了提取,但未设置提取结果。为了使用数据重新呈现列表,我建议将结果设置在Component的状态中。这将触发重新渲染,您应该能够在获取结束后看到列表:

class MyComp extends Component {
    state = { result: [] }
    componentWillMount(){
      this.getMoviesFromApiAsync()
    }

    getMoviesFromApiAsync = () => fetch('https://raw.githubusercontent.com/mudassir21/server/master/newsCategory.json')
     .then((response) => response.json())
     .then((responseJson) => {
        this.setState({ result: responseJson.Cat });
     })
     .catch((error) => {
        console.error(error);
     })

    render(){
      <FlatList data={this.state.result} ... />
    }
}

答案 1 :(得分:1)

阅读此link

使用此代码:

&#13;
&#13;
import React, { Component } from 'react';
import { ActivityIndicator, ListView, Text, View } from 'react-native';

export default class Movies extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isLoading: true
    }
  }

  componentDidMount() {
    return fetch('https://facebook.github.io/react-native/movies.json')
      .then((response) => response.json())
      .then((responseJson) => {
        let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
        this.setState({
          isLoading: false,
          dataSource: ds.cloneWithRows(responseJson.movies),
        }, function() {
          // do something with new state
        });
      })
      .catch((error) => {
        console.error(error);
      });
  }

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

    return (
      <View style={{flex: 1, paddingTop: 20}}>
        <ListView
          dataSource={this.state.dataSource}
          renderRow={(rowData) => <Text>{rowData.title}, {rowData.releaseYear}</Text>}
        />
      </View>
    );
  }
}
&#13;
&#13;
&#13;