【问题标题】:How can I load data from a JSON file which is stored at GitHub in React Native?如何从 React Native 中存储在 GitHub 中的 JSON 文件加载数据?
【发布时间】:2023-03-05 04:57:02
【问题描述】:

我有以下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 文件加载数据。有什么问题?

【问题讨论】:

  • 在 fetch 发生异步时,我会将 fetch 放入 componentWillMount 并将结果设置为状态。然后在渲染中使用 this.state.myjsonresult。如果您将异步函数放在渲染中,它不会在完成时触发重新渲染

标签: json github react-native fetch


【解决方案1】:

由于在呈现列表时会触发您的 fetch,因此不会设置 fetch 的结果。为了用数据重新渲染列表,我建议将结果设置在组件的状态中。这将触发重新渲染,您应该能够在 fetch 解决后看到列表:

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} ... />
    }
}

【讨论】:

    【解决方案2】:

    阅读此link

    使用此代码:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-08
      • 1970-01-01
      • 2017-03-06
      • 1970-01-01
      • 2020-06-25
      相关资源
      最近更新 更多