React Netflix克隆图片渲染失败:Cannot read 'protocol'错误求助
解决React Netflix克隆项目中图片不显示及"Cannot read properties of undefined (reading 'protocol')"错误
问题根源
未传递必要props导致请求失败
App.js中第一个<Row/>组件未传递fetchurl属性,组件渲染时fetchurl为undefined,axios尝试解析无效URL时触发"Cannot read properties of undefined (reading 'protocol')"错误。Row组件title属性传值错误
对应Netflix Originals的Row组件,你将title设置为API地址requests.fetchNetflixOriginals,而非显示用的字符串标题,同时缺少fetchurl属性,会导致标题异常且无法获取电影数据。
修复后的代码
App.js
import './App.css'; import Nav from './Nav'; import Banner from './Banner' import Row from './Row'; import requests from './requests'; function App() { return ( <div className="app"> <Nav/> <Banner/> <Row title="Netflix Originals" fetchurl={requests.fetchNetflixOriginals} isLargeRow={true} /> <Row title="Trending Now" fetchurl={requests.fetchTrending} /> <Row title="Top Rated" fetchurl={requests.fetchTopRated} /> <Row title="Action Movies" fetchurl={requests.fetchActionMovies} /> <Row title="Comedy Movies" fetchurl={requests.fetchComedyMovies} /> <Row title="Horror Movies" fetchurl={requests.fetchHorrorMovies} /> <Row title="Documentaries" fetchurl={requests.fetchDocumentaries} /> </div> ); } export default App;
可选的Row组件容错优化
为避免部分电影无海报/背景图导致显示异常,可添加判断逻辑并补充React列表渲染必需的key属性:
{movies.map((movie) => { const imagePath = isLargeRow ? movie.poster_path : movie.backdrop_path; if (!imagePath) return null; // 跳过无有效图片的电影 return ( <img key={movie.id} src={`${base_url}${imagePath}`} alt={movie.name || movie.title || movie.original_name} /> ) })}
内容的提问来源于stack exchange,提问作者Najad
相关产品推荐
相关产品推荐

