Uncaught TypeError: Cannot read properties of undefined (reading 'poster_path')

Uncaught TypeError: Cannot read properties of undefined (reading 'poster_path')

我有一个从 API 获取数据的异步函数,但是当我使用该数据时,它会收到电影数组未定义的类型错误。但是后来我用“&&”告诉它,如果它是空的,那么不要执行该块,但它仍然会给出错误。我也用三元运算符做过,但还是一样。

这是从API

获取数据的使用效果钩子
const [movies, setMovies] = useState([])
useEffect(() => {

   async function fetchData() {

     const request = await axios.get(fetchUrl);
     setMovies(request.data.results);
     console.log(movies);
     return request;
   }

   fetchData();
}, [fetchUrl]);

这是该元素的代码

{movies &&
    <div id="film-row">
      <FilmCard img={`${base_url}${movies[0].poster_path}`} />
      <FilmCard img={`${base_url}${movies[1].poster_path}`} />
      <FilmCard img={`${base_url}${movies[2].poster_path}`} />
      <FilmCard img={`${base_url}${movies[3].poster_path}`} />
      <FilmCard img={`${base_url}${movies[4].poster_path}`} />
      <FilmCard img={`${base_url}${movies[5].poster_path}`} />
    </div>
}

像这样向您的标签添加 ?

  <FilmCard img={`${base_url}${movies?.[0]?.poster_path}`} />

或 将您的条件渲染更改为:

{movies.length &&

在响应之前正在读取对象。既然可以使用“then.”,为什么还要使用 async await。

useEffect(() => {
axios.get(fetchUrl).then(res => {
  setMovies(res);
})
}, []);

有关此主题的更多信息:https://axios-http.com/docs/api_intro

可能很难记住 JavaScript 将哪些值强制为 true 或 false。在这种情况下,空数组 ([]) 实际上是一个“真实”值 (see MDN for examples),因此您的 FilmCard 元素将被意外渲染。

要么更改您的条件以解决此问题:

{movies.length &&

或将 movies 初始化为“虚假”值:

const [movies, setMovies] = useState(null)

我是这样获取数据的:

useEffect(()=>{
  (async () => {
    const request = await axios.get(fetchUrl);
     setMovies(request.data.results); 
  })()
},[fetchUrl])

而且你应该检查 movies 是否不为空。 在 return 添加

{movies.length > 0 && // What you want to do with movies.}