![](/img/trans.png)
[英]React JS Map TypeError: Cannot read property 'map' of undefined
[英]react js-× TypeError: Cannot read property 'map' of undefined
我有这个代码的问题:TypeError:无法读取未定义的属性“地图”
请指导我该怎么做
应用程序.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>
);```
你错过了这里:
<CardList monters={this.state.monsters}/>
你打电话给你的道具monters
您需要将 data 的默认值设置为空数组,以防您从 fetch 请求中没有收到任何信息。 尝试以下操作:
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.