简体   繁体   English

获取 TypeError: 当在 useEffect 中尝试使用 useState 时,movieDetails.map 不是函数

[英]getting TypeError: movieDetails.map is not a function when try to use useState in useEffect

import { useSelector, useDispatch } from "react-redux";
import { useEffect, useState } from "react";
import request from "../../requests";
import { fetchMovies } from "../../feautures/movies/moviesSlice";
import "./SingleMoviePage.scss";
import Rating from "../../components/UI/Rating/Rating";
import axios from "axios";

const SingleMoviePage = ({ match }) => {
  const dispatch = useDispatch();
  const [movieDetails, setMovieDetails] = useState({})

  /*  params */
  const movieId = match.params.id;
  const page = match.params.page;
  const genre = match.params.genre;

  /* movies reducer handle */
  const movies = useSelector((state) => state.movies.movies);
  const moviesStatus = useSelector((state) => state.movies.status);

  /* movieDetails reducer handle */


  /* base urls */
  const baseImgUrl = "https://image.tmdb.org/t/p/original";
  const movieDetailUrl = `https://api.themoviedb.org/3/movie/${movieId}?api_key=c057c067b76238e7a64d3ba8de37076e&language=en-US`;


  
  useEffect(() => {
    const fetchData = async() => {
      let response = await axios.get(movieDetailUrl);
      response = response.data;
      setMovieDetails(response)
    }

    fetchData()

  },[movieDetailUrl])
  console.log("data: ",movieDetails )

  


  let content;
  if (moviesStatus === "loading") {
    <div>Loading ...</div>;
  } else if (moviesStatus === "succeeced") {
    let movie = movies.find((movie) => movie.id.toString() === movieId);
    content = (
      <div
        className="single-movie__container"
        style={{
          backgroundImage: `url(${
            movie.backdrop_path
              ? baseImgUrl + movie.backdrop_path
              : baseImgUrl + movie.poster_path
          })`,
        }}
      >
        <div className="single-movie__information">
          <h1 className="single-movie__title">{movie.title}</h1>
          <div className="single-movie__rate">
            <Rating
              rating={movie.vote_average}
              className="single-movie__stars"
            />
            <div className="single-movie__average">
              {movie.vote_average}(Imdb)
            </div>
          </div>
          <p className="single-movie__overview">{movie.overview}</p>
          <p className="single-movie__genres">
            <label>Genres</label>
            {
              movieDetails.genres.map(genre => {
                console.log("genre: ",genre)
                return(
                  <div>{genre.name}</div>
                )
              })
            }
          </p>
        </div>
      </div>
    );
  }

  useEffect(() => {
    if (genre === "POPULAR") {
      dispatch(fetchMovies(request.fetchPopular(page)));
    } else if (genre === "NOW PLAYING") {
      dispatch(fetchMovies(request.fetchNowPlaying(page)));
    } else if (genre === "UP COMING") {
      dispatch(fetchMovies(request.fetchUpComing(page)));
    }
  }, [dispatch, genre, page]);

  return <div className="single-movie">{content}</div>;
};

export default SingleMoviePage;

I'm trying to make a movie website with react-redux .我正在尝试使用react-redux制作一个电影网站。 The issue is when I try to get movie details using useEffect and try to map that in:问题是当我尝试使用useEffect获取电影详细信息并尝试将其map到:

<p className="single-movie__genres">

I get TypeError: Cannot read property 'map' of undefined error and I get empty object ( data: {} ) using console.log("data: ", movieDetails) .我得到TypeError: Cannot read property 'map' of undefined error 并且我得到了空对象( data: {} )使用console.log("data: ", movieDetails)

But if I refresh the page everything works well and I get data:但是如果我刷新页面一切正常,我会得到数据:

{
    adult: false, 
    backdrop_path: "/6MKr3KgOLmzOP6MSuZERO41Lpkt.jpg",
    ...
}

using console.log("data: ", movieDetails) .使用console.log("data: ", movieDetails) Why can't I get data when the page is first loaded?为什么我第一次加载页面时无法获取数据?

It is because your initial state does not contain "genres" array inside the object.这是因为您的初始状态不包含对象内的“流派”数组。 And when react tries to handle当反应试图处理

movieDetails.genres.map(...)

it fall down because movieDetails.genres is undefined (and undefined does not support map method of course).它下降是因为 movieDetails.genres 未定义(并且 undefined 当然不支持 map 方法)。 Either include empty array in you initial state like:在初始状态中包含空数组,例如:

const [movieDetails, setMovieDetails] = useState({genres:[]})

or use "?"或使用“?” operator in your chain like:您链中的运算符,例如:

movieDetails.genres?.map(...)

.map method is a prototype function for type array. .map 方法是类型数组的原型函数。 you should declare moviedetails as an array like this when setting the default value using useState hook.在使用useState钩子设置默认值时,您应该将moviedetails声明为这样的数组。

const [movieDetails, setMovieDetails] = useState([])

有一点我不明白。据我所知,第一次加载组件时 useEffect 工作并在 map func 工作后用数据填充我的 movieDetails。我的意思是 js 从上到下工作,不应该填充 movieStatus数据直到涉及到地图功能?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 useEffect 中使用 useState 时,Map 不是函数 - Map is not a function when using useState in useEffect “TypeError:使用 useState 和 useEffect 时无法读取未定义的属性‘名称’” - “TypeError: Cannot read property 'name' of undefined” when using useState and useEffect 如何在useEffect中使用useState? - How to use useState in useEffect? 获取数据时保存数据时useState、UseEffect出现问题 - Problem with useState, UseEffect when saving data when getting data 收到未捕获的TypeError:当我尝试在按钮中使用.tableExport时 - Getting an Uncaught TypeError: when i try to use my .tableExport in a button 电子类型错误:当我尝试使用它时,$(...)。jstree不是函数 - Electron TypeError: $(…).jstree is not a function when i try to use it 在 Netlify 上部署时,在 console.log 中获取“TypeError: (0, t.useState) is not a function” - Getting "TypeError: (0 , t.useState) is not a function" in console.log when deployed on Netlify React JS - Uncaught TypeError: states.map is not a function // useEffect 问题 - React JS - Uncaught TypeError: states.map is not a function // useEffect problem map function里面如何使用useEffect? - How to use useEffect inside map function? 当使用钩子 useState function 从 React TypeError: map is not a function 更改其值时,无法使用 React 更新列表 - Unable to update a list with react when its value is being changed using the hook useState function from React TypeError: map is not a function
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM