【发布时间】:2021-10-03 13:00:57
【问题描述】:
我正在学习 React 并调用 Dog API。我让它用于渲染图像,但是当我尝试渲染多个图像时,它不起作用。对于上下文,API 调用链接是https://dog.ceo/api/breeds/image/random/5,其中“/5”指定图像的数量。我很确定正在设置状态,因为当我放置 console.log 而不是设置状态时,它给了我带有图像 URL 的 JSON。我收到一条错误消息“无法读取未定义的属性 'map'”。
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [],
}
}
componentDidMount() {
fetch("https://dog.ceo/api/breeds/image/random/5")
.then(response => response.json())
.then(json => this.setState({data: json}));
}
render() {
return (
<div>
{this.state.data.message.map((item, id) => (
<img src={item} key={id} alt="dog" />
))}
</div>
)
}
}
export default App;
【问题讨论】:
标签: javascript reactjs