首页 > 解决方案 > 在 React Native 中从 fetch 中导出 JSON

问题描述

我正在导出从 fetch 中获得的 JSON。我知道我有一个绑定问题,但我不完全确定应该如何将我的函数绑定到当前组件。我在这个 URL https://snack.expo.io/@mcmillster/c21pbG有一个简单的例子。

应用程序.js

  import React from 'react';
    import { FlatList, ActivityIndicator, Text, View  } from 'react-native';
    import { getMovies } from './utility.js';

    export default class FetchExample extends React.Component {

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

    componentDidMount(){
    this.getMovies;
    }



    render(){

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

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

实用程序.js

export function getMovies() {
    return fetch('https://facebook.github.io/react-native/movies.json')
      .then((response) => response.json())
      .then((responseJson) => {

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

        });

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

标签: react-native

解决方案


在你的componentDidMount生命周期钩子中,你不是在调用getMovies函数,你只是在引用它。更改this.getMoviesthis.getMovies()

解决方案

componentDidMount(){
  this.getMovies();
}

推荐阅读