简体   繁体   中英

React: Function Map doesn't work in my render()

I want to manipulate my JSON's datas but it doesn't work. For now, my file is in local. I'll change that later. Here is my code

db.json

{
    "test": "true false",
    "quotesList" : [
        {
            "id": 1,
            "quote": "Celebrity is the religion of our time",
            "source": "Maureen Dowd"
        },
        {
            "id": 2,
            "quote": "Nothing is permanent in this wicked world not even our troubles",
            "source": "Charlie Chaplin"
        },
        {
            "id": 3,
            "quote": "It always seems impossible until it's done",
            "source": "Nelson Mandela"
        },
        {
            "id": 4,
            "quote": "Music isn't for the eyes, it's for the ears",
            "source": "Adele"
        },
        {
            "id": 5,
            "quote": "The first step is you have to say that you can",
            "source": "Will Smith"
        }
    ]
}

Quote.js

import React from 'react';

/*import axios from 'axios';*/

import database from '../../db.json';

export default class Quote extends React.Component {

  render() {
    const elem = database.quotesList
    return (
        <ul>
            {Object.keys(elem).map((v, i) => <li key={i}>{v.id}</li> )}
        </ul>
    )
  }
}

Home.js

import React from 'react'
import Quote from '../../component/Quote/Quote'


export const Home = () => {
    return (
        <div>
            <p>Hello Home</p>
            <Quote />
        </div>
    )
}

I did few tests and I think the problem is the map() function. But I don't know how to fix it.

Thanks by advance

You don't need Object.keys since elem , your database.quotesList , is already an array.

Changing it to

{elem.map((v, i) => <li key={i}>{v.id}</li> )}

should do the trick

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