React调用TMDB API获取单条电影数据时map函数报错求助
解决React中遍历单条API返回数据时的map报错问题
问题场景
调用TMDB的单条电影查询API,该接口返回单个电影对象(无results这类数组字段)。在React状态管理中current初始化为数组,调用searchById获取数据后直接通过setCurrent(data)更新状态,组件内使用current.map遍历数据时触发报错:
Details.js:22 Uncaught TypeError: Cannot read properties of null (reading 'map')
报错原因
API返回的是单个对象,直接将其赋值给初始为数组的current后,current的类型从数组变成了对象。而对象不存在map方法,因此调用map会抛出类型错误。
原代码示例
状态管理代码
const [current, setCurrent] = useState([]); const searchById = (movieId) => { fetch(API_SEARCH_BY_ID + movieId + API_KEY) .then((res) => res.json()) .then((data) => { console.log(data); setCurrent(data); console.log(current); successAlert(); }); };
组件遍历代码
<Container fluid> {current.map((current, currentReq) => ( <MovieDetails current={current} key={currentReq.id} {...currentReq}></MovieDetails> ))} </Container>
解决方法
将API返回的单个对象放入数组中,再更新状态,确保current始终保持数组类型,这样就能正常使用map遍历:
const searchById = (movieId) => { fetch(API_SEARCH_BY_ID + movieId + API_KEY) .then((res) => res.json()) .then((data) => { console.log(data); const test = [data] setCurrent(test); successAlert(); }); };
内容的提问来源于stack exchange,提问作者Ciyradyl
相关产品推荐
相关产品推荐

