javascript - undefined 不是 React Native 中的对象(评估 'item.Title')
问题描述
所以我正在制作这个电影浏览器项目,其中我必须从 OMDb API(http://www.omdbapi.com/)获取数据并在 Flatlist 组件中显示数据。
虽然我设法显示每部电影搜索的 10 个结果(因为 API 在每次调用时返回 10 个项目),但我添加了一个按钮,该按钮将运行一个函数以使用 page 参数再次向 API 发送请求,获取 10 个更多结果和将结果连接到电影。
但是,只要我按下按钮并运行该功能,就会出现此错误undefined is not an object (evaluating 'item.Title')
。
这是我的 Home 组件代码 => Home.js
import React, { useState, useEffect } from 'react';
import { StyleSheet, View, Text, FlatList, TouchableHighlight, Image, Button} from 'react-native';
import { TextInput } from 'react-native-gesture-handler';
import { fetchMovies } from "../api/api";
export default class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
text: "",
movies: null,
};
}
//update search text
componentDidUpdate(prevState) {
if (this.state.text !== prevState.text) {
this.getSearch(this.state.text);
}
}
//get search results from fetchMovies
getSearch = async text => {
const results = await fetchMovies(text)
this.setState({ movies: results });
};
////////////////////////////Function making API call using the page parameter///////////
//loading more movies
handleLoadMore = async() => {
try {
const page = Math.trunc(this.state.movies.length / 10) + 1;
const res = await fetchMovies(this.state.text, page);
this.setState(prevState => ({
movies: prevState.movies.concat(res.movies)
}))
}catch(err){
console.log(err.message);
}
}
//////////////////////////////////////////////////////////
//movie title and poster to render in the flatlist
movieCard = ({ item }) => {
return (
<TouchableHighlight
style={styles.movieCard}
underlayColor="white"
onPress={() => {
this.props.navigation.navigate("Details", {
title: item.title,
id: item.imdbID
});
}}
>
<View>
<Image
style={styles.movieImage}
source={ {uri: item.Poster} }
/>
<View style={{alignItems: 'center'}}>
<Text style={styles.movieTitle}>{item.Title} ({item.Year})</Text>
</View>
</View>
</TouchableHighlight>
);
};
render() {
return(
<View style={styles.container}>
<TextInput
style={styles.searchBox}
autoCorrect={false}
autoCapitalize='none'
autoFocus maxLength={45}
placeholder='Search'
onChangeText={(text) => this.setState({ text })}
value={this.state.text}
/>
{this.state.movies ?
<FlatList
style={styles.movieList}
data={this.state.movies}
renderItem={this.movieCard}
keyExtractor={item => item.Title + item.imdbID}
/>
:
<Text
style={{
alignSelf: 'center',
paddingTop: 150,
justifyContent: 'center',
color: '#8a8787',
fontStyle: 'italic' }}>
search for a movie above...
</Text>
}
<Button
onPress={this.handleLoadMore}
title="Load More"
color="#841584"
/>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 20,
backgroundColor: '#DDD',
alignItems: 'center',
},
searchBox: {
fontSize: 20,
fontWeight: '300',
padding: 10,
width: '100%',
backgroundColor: 'white',
borderRadius: 10,
marginBottom: 30
},
movieList: {
flex: 1,
marginHorizontal: 30,
},
movieCard: {
flex: 1,
margin: 5,
padding: 5,
},
movieImage: {
width: '100%',
height: 350,
borderRadius: 10,
alignSelf: 'center',
},
movieTitle: {
marginTop: 10,
fontSize: 20,
color: '#333'
}
});
这是 api 函数的代码 => api.js
const API_KEY = "API_KEY";
//fetch search data from omdb api
export const fetchMovies = async (response, page) => {
const url = `http://www.omdbapi.com/?apikey=${API_KEY}&s=${response}`;
try {
let response = await fetch(url);
if(page) {
response = await fetch(url + `&page=${page}`)
}
const { Search } = await response.json();
return Search;
} catch (err) {
return console.log(err);
}
};
//fetch ID from omdb api
export const fetchById = async id => {
const url = `http://www.omdbapi.com/?apikey=${API_KEY}&i=${id}`;
try {
const response = await fetch(url);
const results = await response.json();
return results;
} catch (err) {
return console.log(err);
}
};
我知道解决这个问题可能很简单,但是对于 react-native 我是新手,我无法弄清楚。
解决方案
关于FlatList
,在文档中,他们显然传递了 lambda,它将渲染的项目返回给renderItem
prop
你的初始化state.movies
也是空的,我认为它应该是一个空数组
this.state = {
text: "",
movies: [],
};
<FlatList
style={styles.movieList}
data={this.state.movies}
renderItem={({item}) => this.movieCard({item})}
keyExtractor={item => item.Title + item.imdbID}
推荐阅读
- elasticsearch - SQL Server 数据库 > Logstash > Elasticsearch:将与同一实体相关的结果集记录映射到同一 ES 文档
- android - 安卓 Facebook 登录。防止按钮更改为“注销”
- flutter - 如何使用 Flutter Web 将数据保存在浏览器的 cookie 中?
- java - 使用 Maven Shade 构建应用程序 jar 时,排除所有 META-INF/versions 目录/文件是否安全?
- amazon-dynamodb - 查询 DynamoDB 表以按创建日期获取前 100 条记录的顺序
- excel - 记住位于另一列的一列中的公式的前一个值
- python-3.x - 如何将生成的 AsyncResult 传递给 FastAPI python 中的其他 API
- ansible - 来自 ansible 插件的动态库存组:nmap
- node.js - 将数组项推送到 mongoDb 中的数组类型列
- java - java - 如何使用Java中的嵌套for循环为矩形模式创建(m)列和(n)行?