【问题标题】:TypeError: movies is undefined using React HooksTypeError:电影未使用 React Hooks 定义
【发布时间】:2021-10-12 03:53:05
【问题描述】:

我正在使用 React 钩子将数据从 API 导入到数组中,我收到错误 TypeError: movies is undefined。

这是我的完整代码:

import React, { useEffect , useState } from 'react';
import axios from './axios';
import "./Row.css";

function Row({ title, fetchUrl, isLargeRow = false}) {
    const [movies, setMovies] = useState([]);
    const base_url = "https://image.tmdb.org/t/p/original/";

    useEffect(() => {
        async function fetchData(){
            const request = await axios.get(fetchUrl);
            setMovies(request.data.results);
            return request;
        }

        fetchData();
    }, [fetchUrl]);

    console.log(movies);

    return (
        <div className="row">
        <h2>{title}</h2>

        {movies.map(movie => (
            <img src={`${base_url}${
               isLargeRow ? movie.poster_path : movie.backdrop_path 
            }`}
            alt={movie.name}
            />

        ))}
        </div>
    );
}

export default Row;

当我做 console.log(movies); ,在它显示一些带有数据的数组之前,我似乎得到了一些空数组。我想知道这个错误是不是因为前几个数组中没有值。

Image showing arrays in the console

The error itself

【问题讨论】:

    标签: javascript html reactjs typescript react-hooks


    【解决方案1】:

    更新答案:当电影中没有任何元素时,您正在尝试从电影数组中读取。您可能希望有条件地渲染组件,以便在设置电影后渲染它。

     {movies && movies.map(movie => (
            <img src={`${base_url}${
               isLargeRow ? movie.poster_path : movie.backdrop_path 
            }`}
            alt={movie.name}
            />
    
        ))}
    

    类似的东西。

    【讨论】:

      猜你喜欢
      • 2021-05-30
      • 2020-06-22
      • 2021-04-08
      • 2021-03-10
      • 1970-01-01
      • 2018-07-29
      • 2017-08-08
      • 1970-01-01
      • 2021-07-31
      相关资源
      最近更新 更多