我正在尝试将API数据呈现到页面上,但是得到这个错误--未定义的不是函数(接近‘...movies.map.’)--如何在页面中标记我的结果?为什么在movie.title中给我红色的错误?
import { StatusBar } from 'expo-status-bar';
import React ,{useState,useEffect} from 'react';
import {ActivityIndicator, FlatList, Text,View} from 'react-native'
import MovieBox from '../components/MovieBox';
import { Ionicons } from '@expo/vector-icons';
import styled from 'styled-components/native'
import Header from '../components/Header';
export default function Home() {
const apiPath = "https://api.themoviedb.org/3/movie/popular?
api_key=i don't want to show"
const [movies,setMovies]=useState<any[]>([])
useEffect(()=>{
fetch(apiPath)
.then(response=>response.json())
.then(res=>setMovies(res))
.catch(err=> console.log(err))
},[])
return (
<>
<StatusBar
translucent
backgroundColor='transparent'
/>
<Container>
<Text>
{
movies.map(movie=>(
<Text>{movie.title}</Text>
))
}
</Text>
<Header/>
</Container>
</>
)
}发布于 2022-09-26 16:35:32
问题:
moviedb api v3返回一个带有结果数组的object,如下例所示:
{
"page": 1,
"results": [
{
"adult": false,
"backdrop_path": "/2RSirqZG949GuRwN38MYCIGG4Od.jpg",
"genre_ids": [
53
],
"id": 985939,
"original_language": "en",
"original_title": "Fall",
"overview": "For best friends Becky and Hunter, life is all about conquering fears and pushing limits. But after they climb 2,000 feet to the top of a remote, abandoned radio tower, they find themselves stranded with no way down. Now Becky and Hunter’s expert climbing skills will be put to the ultimate test as they desperately fight to survive the elements, a lack of supplies, and vertigo-inducing heights",
"popularity": 8806.711,
"poster_path": "/spCAxD99U1A6jsiePFoqdEcY0dG.jpg",
"release_date": "2022-08-11",
"title": "Fall",
"video": false,
"vote_average": 7.5,
"vote_count": 951
}
],
"total_pages": 35227,
"total_results": 704530
}这就是为什么当您试图从对象非数组映射时出现错误的原因。
解决方案:
要解决这个问题,您需要像这样从setMovies从res.results获得以下信息:
useEffect(()=>{
fetch(apiPath)
.then(response=>response.json())
.then(res=> setMovies(res.results))
.catch(err=> console.log(err));
},[]);备注:
我找不到你们Container的进口品。
2-我更希望你改变地图的位置,让它在视图中,而不是像这样的文本:
<View>
{
movies.map(movie=>(
<Text>{movie.title}</Text>
))
}
</View>希望您发现这有帮助,下面是一个工作示例的链接,只需添加您的api键即可使其工作。
https://stackoverflow.com/questions/73856781
复制相似问题