我看到的是一个常见错误,我尝试了不同的解决方案,但没有结果。
到目前为止,这是我的代码,很少能正常工作,并且获取返回的是正确的电影数组,但大多数情况下都是发回错误:
import React, { useState, useEffect } from "react";
import { Text, View, Image, ScrollView, ActivityIndicator } from "react-native";
function Dashboard() {
const [loading, setLoading] = useState(true);
const [popularMovies, setPopularMovies] = useState([])
const popularMoviesUrl =
".....";
const fetchMovies = () => {
fetch(popularMoviesUrl)
.then(res => res.json())
.then(setPopularMovies)
.then(console.log(popularMovies));
};
useEffect(() => {
fetchMovies();
}, []);
const { results } = popularMovies;
return loading ? (
<View style={styles.loader}>
<ActivityIndicator size="large" color="#dcae1d" animating />
</View>
) : (
<ScrollView horizontal style={styles.container}>
{results.map(movie => (
<View key={movie.id}>
<Text style={styles.container}>{movie.title}</Text>
<Image
style={styles.poster}
source={{
uri: `https://image.tmdb.org/t/p/w500${movie.poster_path}`
}}
/>
</View>
))}
<Text>thfh</Text>
</ScrollView>
);
}
export default Dashboard;
答案 0 :(得分:0)
似乎是一个问题,涉及从您获取的内容中返回的热门电影。从您的抓取中将您的PopularMovies状态设置为results
属性,而不是JSON。
所以改变:
.then(setPopularMovies)
到...
.then(resJson => setPopularMovies(resJson.results))
然后删除结果变量并直接引用PopularMovies。