简体   繁体   中英

react js-× TypeError: Cannot read property 'map' of undefined

I have an issue with this code: TypeError: Cannot read property 'map' of undefined

Please guide me on what to do

app.js

import React from "react";

import {CardList} from "./componets/card-list/card-list";


class App extends React.Component {
    constructor() {
        super();
        this.state={
            monsters:
                []
        };
    }
    componentDidMount() {
        fetch('http://jsonplaceholder.typicode.com/users')
            .then(res => res.json())
            .then((data) => {
                this.setState({ monsters: data })
            })
    }
    render() {
     return(
         <div>
             <CardList monters={this.state.monsters}/>
         </div>
     )
 }
}
export default App;

and cardlist.jsx Please guide me on what to do

import './card-list.css'


export const CardList=(props) => (

     <div className='card-list'>{props.monsters.map(monster =>(<h1 key={monster.id}>{monster.name}</h1>))}

    </div>
);```


You missed here:

<CardList monters={this.state.monsters}/>

You called your prop monters

You need to set the default value of data to empty array incase you receive nothing from the fetch request. Try following:

import React from "react";

import {CardList} from "./componets/card-list/card-list";


class App extends React.Component {
    constructor() {
        super();
        this.state={
            monsters:
                []
        };
    }
    componentDidMount() {
        fetch('http://jsonplaceholder.typicode.com/users')
            .then(res => res.json())
            .then((data = []) => {
                this.setState({ monsters: data })
            })
    }
    render() {
     return(
         <div>
             <CardList monters={this.state.monsters}/>
         </div>
     )
 }
}
export default App;

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