-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApp.js
108 lines (97 loc) · 2.61 KB
/
App.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
import React, { Component } from "react";
import { Image, FlatList, StyleSheet, Text, View } from "react-native";
var REQUEST_URL ="http://193.112.44.172/movie.json";
export default class SampleAppMovies extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
loaded: false
};
// 在ES6中,如果在自定义的函数里使用了this关键字,则需要对其进行“绑定”操作,否则this的指向会变为空
// 像下面这行代码一样,在constructor中使用bind是其中一种做法(还有一些其他做法,如使用箭头函数等)
this.fetchData = this.fetchData.bind(this);
}
componentDidMount() {
this.fetchData();
}
_keyExtractor = (item, index) => item.id;
fetchData() {
fetch(REQUEST_URL)
.then(response => response.json())
.then(responseData => {
// 注意,这里使用了this关键字,为了保证this在调用时仍然指向当前组件,我们需要对其进行“绑定”操作
this.setState({
data: this.state.data.concat(responseData.movies),
loaded: true
});
})
.catch(error => {
console.error(error);
});
}
render() {
if (!this.state.loaded) {
return this.renderLoadingView();
}
return (
<FlatList
data={this.state.data}
renderItem={this.renderMovie}
keyExtractor={this._keyExtractor}
style={styles.list}
/>
);
}
renderLoadingView() {
return (
<View style={styles.container}>
<Text>Loading movies...</Text>
</View>
);
}
renderMovie({ item }) {
// { item }是一种“解构”写法,请阅读ES2015语法的相关文档
// item也是FlatList中固定的参数名,请阅读FlatList的相关文档
return (
<View key={{key:item.id}} style={styles.container}>
<Image
source={{ uri: item.posters.thumbnail }}
style={styles.thumbnail}
/>
<View style={styles.rightContainer}>
<Text style={styles.title}>{item.title}</Text>
<Text style={styles.year}>{item.year}</Text>
</View>
</View>
);
}
}
var styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: "row",
justifyContent: "center",
alignItems: "center",
backgroundColor: "#F5FCFF"
},
rightContainer: {
flex: 1
},
title: {
fontSize: 20,
marginBottom: 8,
textAlign: "center"
},
year: {
textAlign: "center"
},
thumbnail: {
width: 53,
height: 81
},
list: {
paddingTop: 20,
backgroundColor: "#F5FCFF"
}
});