我正在尝试从 jsonPlaceholder 加载图片。当我console.log出图像数组时,它工作成功。当我尝试从元素调用 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;
最佳答案
问题出现在多个 setState
中。一旦你设置了State,它就会异步更新和渲染
。所以没有等待next
setState。最好在一次调用中设置这两个数据。
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)})
}
您可以像这样清理代码:
工作岗位: https://codesandbox.io/s/articlepodcast-wd2rv?file=/home.js:0-1214
import React, { Component } from "react";
import axios from "axios";
class Home extends Component {
constructor(props) {
super(props);
this.state = {
posts: [],
images: []
};
}
componentDidMount = async () => {
const res = await axios.get("https://jsonplaceholder.typicode.com/posts");
const res2 = await axios.get("https://jsonplaceholder.typicode.com/photos");
this.setState({
posts: res.data.slice(0, 10),
images: res2.data.slice(0, 10)
});
};
render = () => {
const { posts, images } = this.state;
const PostList = posts.length ? (
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>{images[index].url} </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;
关于javascript - 类型错误 : Cannot read property 'url' of undefined for JSONPlaceholder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61167433/