简体   繁体   中英

How to return a mapped array in JSX?

I have imported some dummyData (1000 objects of films) to my React.js Component and I want to render the titles.

export const dummyData = [
  {
    id: 'tt0111161',
    rank: '1',
    title: 'The Shawshank Redemption',
  }

I have created an array with the whole object and I wish to show the first 3 movies.

const likedFilms = [];
for (let i = 0; i < 3; i++) {
    likedFilms.push(dummyData);
}

The issues I am having is to render the title.

I have tried using this. and without. Not sure how to access this data...

return (
        <div>
    {likedFilms.map((likedFilm) => <p>TITLE: {likedFilms.title} </p>)}
 </div> )

or TITLE: {this.likedFilms.title} 

Mapping does work as it shows me: TITLE: TITLE: TITLE:

But it doesnt render the title.

编辑您的回报,您正在访问 likeFilm S而不是 likeFilm,在示例中我已将名称更改为 film

{likedFilms.map(film => <p>TITLE: {film.title} </p>)}
{likedFilms.map((likedFilm) => <p>TITLE: {likedFilm.title} </p>)}

likedFilmed is the name of your array whereas likedFilm is the name of each item in the array when you are iterating. So inside the map's return, you want to access the individual item's property likedFilm.title instead of likedFilms

I also recommend giving a key to the p element to get rid of React's console warning; so assuming the film titles are unique, it would become

{likedFilms.map((likedFilm) => <p key={likedFilm.title}>TITLE: {likedFilm.title} </p>)}

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