【发布时间】:2020-07-24 19:18:36
【问题描述】:
我正在尝试从 jsonPlaceholder 加载图片。当我控制台注销图像数组时,它可以成功运行。当我尝试从元素调用 URL 时,它会引发 TypeError。我试着用异步的方式来做,即使这样也行不通。有什么解决方法吗?可能是什么问题?
import React, {Component} from 'react';
import axios from 'axios';
class Home extends Component{
state = {
posts : [],
images : []
};
componentDidMount = async () => {
const res = await axios.get('https://jsonplaceholder.typicode.com/posts');
this.setState({posts: res.data.slice(0,10)})
const res2 = await axios.get('https://jsonplaceholder.typicode.com/photos');
this.setState({images: res2.data.slice(0,10)})
}
render = () => {
const {posts} = this.state.posts;
const {images} = this.state.images;
const PostList = this.state.posts.length ? (
this.state.posts.map((post,index) => {
return(
<div className = "post card" key = {post.id}>
<div className = "card-content">
<div className = "card-title">
{post.title}
</div>
<div className>
{(this.state.images[index].url)} //console.log(this.state.images[index] works, but .URL doesn't
</div>
<div>
<p>{post.body}</p>
</div>
</div>
</div>
)
})) : (<div className = "center">No Posts!</div> )
return(
<div className = "container">
<div className = "center">
{PostList}
</div>
</div>)
}
}
export default Home;
【问题讨论】:
-
它是 thumbnailUrl,而不是 url
-
如果您是数组映射中的 console.log(this.state.images[index]),您每次都会得到什么
标签: javascript json reactjs react-redux react-router