promise - 无法读取未定义的 'file_path'属性?为什么?

标签 promise react-hooks fetch syntax-error undefined

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/

相关文章:

reactjs - 尽管依赖项没有变化,useEffect 仍运行无限循环

javascript - 尽管有 catch block ,但 fetch 仍然会抛出异常

php - MySQLI 准备语句 : num_rows & fetch_assoc

python - 不使用 RegEx、BeautifulSoup、lXml 等查找两个单词之间的内容

javascript - 在 react redux 中重定向之前如何等待操作完成?

javascript - 从 React 自定义 Hook 调用的函数返回 'is not a function'

reactjs - 如何在 React 上呈现异步内容?

javascript - 我如何在 React 中使用钩子(Hook)预初始化状态?

promise - Bluebird .then方法

javascript - 同步链接 Promise