React中使用map函数结合Bootstrap卡片渲染对象数组报错求助
错误原因
- 核心错误是
useState返回值使用混淆:const [trendingResults, setTrendingResults] = useState([])中,trendingResults才是存储接口返回数组的状态变量,setTrendingResults是专门用来修改该状态的函数,函数本身不存在map方法,你误将setter函数作为了map的调用对象。 - 次要问题1:
useEffect未添加空依赖数组,会导致组件每次渲染都重复发起接口请求,造成性能损耗。 - 次要问题2:React中指定元素CSS类需要使用
className属性,你在<img>和<Link>标签中写的class属性不会生效,还会抛出控制台警告。
修正后可运行代码
import Hero from "./Hero"; import Footer from "./Footer"; import { Link } from "react-router-dom"; import { useParams } from "react-router-dom"; import { useEffect, useState } from "react"; const TrendingCard = ({ trending }) => { const trendPosterUrl = `https://image.tmdb.org/t/p/w500${trending.poster_path}`; const trendDetailUrl = `/movies/${trending.id}`; return ( <div className="col-lg-4 col-md-3 col-2"> <div className="card"> <img src={trendPosterUrl} className="card-img-top" alt={trending.original_title} /> <div className="card-body"> <h5 className="card-title">{trending.original_title}</h5> <Link to={trendDetailUrl} className="btn btn-primary"> Show details </Link> </div> </div> </div> ); }; const TrendingView = (data) => { const [trendingResults, setTrendingResults] = useState([]); useEffect(() => { fetch( "https://api.themoviedb.org/3/trending/movie/week?api_key=776d38251dae661e04c01631cfa95286" ) .then((response) => response.json()) .then((data) => { setTrendingResults(data.results); }); }, []); // 添加空依赖数组,仅组件挂载时发起一次请求 // 改为对状态变量trendingResults调用map const trendingHtml = trendingResults.map((obj, i) => { return <TrendingCard trending={obj} key={i} />; }); return ( <div> <Hero text="Trending" /> {trendingHtml && ( <div className="container"> <div className="row">{trendingHtml}</div> </div> )} </div> ); }; export default TrendingView;
内容的提问来源于stack exchange,提问作者tinaa
相关产品推荐
相关产品推荐

