react-native - 在 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);
});
}
解决方案
在你的componentDidMount
生命周期钩子中,你不是在调用getMovies
函数,你只是在引用它。更改this.getMovies
为this.getMovies()
解决方案
componentDidMount(){
this.getMovies();
}
推荐阅读
- python - 将 conda 环境迁移到没有互联网(或快速互联网)的机器
- c# - AutoMapper 跳过源上所有为空的成员
- angular - 如何从父组件重置子组件中的字段 - 角度
- hibernate - 使用 JoinColumns 时,双向 Hibernate 查询产生 1+ N 个查询
- angular - How to call a method from another component in Angular?
- java - Sqlite 数据库不删除条目
- angular - 单击角度 6 中的按钮时调用不同的函数
- laravel - VueJs 和 Laravel。我无法使用 Vuejs 和 FileReader 发送 excel 文件
- jquery - 在构造表时使用 if 语句
- python-3.x - 如何正确关闭正在流式传输网络摄像头镜头的套接字?