getImage是返回actor的URL所需的promise序列。有时有效,有时会中断,错误是:
Uncaught (in promise) TypeError: Cannot read property 'file_path' of undefined at getActorImage
码:
const getImage = async() => {
const page = getRandomInt(1,40);
const movielist = `https://api.themoviedb.org/3/movie/popular?&api_key=${key}&page=${page}`
const resp = await fetch(movielist);
const {results} = await resp.json();
const movieid = results[getRandomInt(0,results.length)].id
const castlist = `https://api.themoviedb.org/3/movie/${movieid}/credits?&api_key=${key}`
const resp2 = await fetch(castlist);
const {cast} = await resp2.json();
const id = cast[0].id;
const actor = `https://api.themoviedb.org/3/person/${id}/images?api_key=${key}`
const resp3 = await fetch(actor);
const {profiles} = await resp3.json();
const aux = profiles[0].file_path;
const url = `https://www.themoviedb.org/t/p/w600_and_h900_bestv2/${aux}`;
return (
url
)}
const useFetchActor = () => {
const [state, setstate] = useState({
path:'',
loading:true
})
useEffect( () =>{
getImage()
.then( image =>{
setstate({
path:image,
loading:false
})
})
},[])
return state;
}
最佳答案
有些 Actor 没有photo_path
,这就是为什么它显示undefined
的原因。如果强制转换没有photo_path
,则可以返回一条语句并结束函数,并显示错误消息
// In getImage function
..
if (cast.length === 0 || !cast[0].profile_path) {
return "photo not found";
} else {
const id = cast[0].id;
const actor = `https://api.themoviedb.org/3/person/${id}/images?api_key=${key}`;
const resp3 = await fetch(actor);
const { profiles } = await resp3.json();
const aux = profiles[0].file_path;
const url = `https://www.themoviedb.org/t/p/w600_and_h900_bestv2/${aux}`;
return url;
}
};
// In useFetchActor function
..
useEffect(() => {
getImage().then((res) => {
console.log(res);
if (res === "photo not found") {
setImgNotFound(true);
return;
}
setstate({
path: res,
loading: false
});
});
}, []);
return imgNotFound ? (
<p>There is no image for this actor</p>
) : (
<img src={state.path} alt="actor" />
);
Codesandbox sample
关于promise - 无法读取未定义的 'file_path'属性?为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65785027/