You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React开发电影API时出现TypeError: undefined is not an object (evaluating 'movies.map')报错

报错根因

你在render函数中是从props中提取movies变量,未设置默认值,父组件未传递该属性/传递时异步请求还未返回时,movies就是undefined,调用map方法自然会抛出错误。

修复方案

  1. 修正movies的取值逻辑并加兜底
    如果你要使用组件自身state中初始化的movies数组,把render里的解构语句修改为:
    const { FavoriteMovies, validated, movies } = this.state;
    
    如果你确定是从父组件获取movies,解构时加默认值避免undefined:
    const { movies = [] } = this.props;
    
  2. 修复map回调的变量重名问题
    把map的回调参数名改为movie,和外层的movies数组区分开,对应引用属性的地方同步修改,避免逻辑混乱:
    movies.map((movie) => {
      if (movie._id === FavoriteMovies.find((favMovie) => favMovie === movie._id)) {
        // 内部所有movies.xxx都替换为movie.xxx
        return (
          <CardDeck className="movie-card-deck">
            <Card className="favorites-item card-content" style={{ width: '16rem' }} key={movie._id}>
              <Card.Img style={{ width: '18rem' }} className="movieCard" variant="top" src={movie.ImagePath} />
              <Card.Body>
                <Card.Title className="movie-card-title">{movie.Title}</Card.Title>
                <Button size='sm' className='profile-button remove-favorite' variant='danger' value={movie._id} onClick={(e) => this.removeFavoriteMovie(e, movie)}>
                  Remove
                </Button>
              </Card.Body>
            </Card>
          </CardDeck>
        );
      }
    })
    
  3. 修复removeFavoriteMovie方法的参数缺失问题
    你在点击事件中传递了事件和当前电影对象,但是方法没有接收参数,同时内部引用的movies._id未定义,修改方法:
    removeFavoriteMovie(e, movie) {
      const token = localStorage.getItem('token');
      const username = localStorage.getItem('user');
      
      axios.delete(`https://nhas-flixdb-2021.herokuapp.com/users/${username}/movies/${movie._id}`, {
          headers: { Authorization: `Bearer ${token}` },
        })
        .then(() => {
          alert('Movie was removed');
          this.getUser(token); // 不要直接调用componentDidMount,调用getUser即可刷新用户收藏数据
        })
        .catch(function (error) {
          console.log(error);
        })
    }
    
  4. 补全全量电影列表的获取逻辑
    如果你是用组件state里的movies存储全量电影列表,需要在componentDidMount中新增请求获取所有电影数据,并存入state的movies字段,否则movies一直是空数组,即使没有报错也渲染不出内容。

内容的提问来源于stack exchange,提问作者nvhii

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 20:39:03