反应js-×TypeError:无法读取未定义的属性“地图”

时间:2020-04-01 10:22:41

标签: javascript reactjs

我对以下代码有疑问: TypeError:无法读取未定义的属性“地图”

请指导我该怎么做

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;

和cardlist.jsx 请指导我该怎么做

import './card-list.css'


export const CardList=(props) => (

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

    </div>
);```


2 个答案:

答案 0 :(得分:3)

您错过了这里:

{featureSubtitle && featureSubtitle ? (
                  <div
                    dangerouslySetInnerHTML={{ __html: featureSubtitle }}
                  />
                ) : null}

您称自己的道具为<CardList monters={this.state.monsters}/>

答案 1 :(得分:0)

您需要将数据的默认值设置为空数组,以防从获取请求中接收不到任何信息。尝试以下操作:

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;