react js-× TypeError:无法读取未定义的属性“map”
2020-04-01
110
我对这段代码有疑问: TypeError:无法读取未定义的属性“map”
请指导我该怎么做
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个回答
您错过了这里:
<CardList monters={this.state.monsters}/>
您将您的道具命名为
monters
Mark Minerov
2020-04-01
您需要将数据的默认值设置为空数组,以防您从获取请求中没有收到任何内容。请尝试以下操作:
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;
ziishaned
2020-04-01