简体   繁体   中英

React: Cannot read property 'map' of undefined

Code is here .

What I'm trying to do:

Trying to have the list of movies display, when fetched with Axios, to the area on the right of the app.

I'm not sure if this is a passing prop issue, or if it's something else. Any hints as to what's going on?

import React from "react";
import Card from "@material-ui/core/Card";
import Grid from "@material-ui/core/Grid";

import "../Movie/_movie.scss";

const Movie = props => {
  return (
    <div>
      <Grid container>
        <Grid item xs={12} md={12}>
          <Card>
            <h3>Movies should show up here</h3>
            <ul>
              {props.movies.map(movie => (
                <li key={movie.id}>
                  <img
                    src={`https://image.tmdb.org/t/p/w185/${movie.poster_path}`}
                  />
                  <h3>{movie.original_title}</h3>
                  <p>Date: {movie.release_date}</p>{" "}
                  <p>Rating: {movie.vote_average}/10</p>
                  <p>{movie.overview}</p>
                </li>
              ))}
            </ul>
          </Card>
        </Grid>
      </Grid>
    </div>
  );
};

export default Movie;

What's most likely happening is your render function is running before the api call has had time to complete, thus props.movies is undefined at the time when render needs it. What you can do is either give props.movies a default value of an empty array [] or you can first check to see if props.movies is defined before mapping by doing props.movies && props.movies.map .

访问电影对象时,添加检查props.movies && props.movies.map(movie=>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM