合并来自 JsonPlaceholder 的两个 API



我是编码新手,正在构建博客应用程序。我正在使用 axios 对 Jsonplaceholder 进行 api 调用。我正在尝试映射呈现标题、描述和名称的div,但不断收到错误。关于如何合并 api 调用的任何想法,甚至是更好的编码方法?

这是我的代码:

import React from 'react'
import axios from 'axios'
import '../Styles/content.css'
class Content extends React.Component {
state ={
posts: [],
users: []
}
componentDidMount() {
axios.get('https://jsonplaceholder.typicode.com/posts?_start=10&_limit=10')
.then(resp => resp.data)
.then((data) => {
this.setState({posts: data})
console.log(this.state.posts)
}).then(
axios.get('https://jsonplaceholder.typicode.com/users')
.then(resp => resp.data)
.then((data) => {
this.setState({users: data})
console.log(this.state.users)
})
)    
}
render() {
return (
<div className='contentContainer'>
{this.state.posts.map(post => (
<div className='blogs'key={post.id}>
<div className='blogsPost'>
<p className='postTitle'>{post.title}</p>
<p className='postbody'>{post.body}</p>
</div>
{this.state.users.filter(user => (
<div className='blogsUsers'>
<p>{user.name}</p>
</div>
))}
</div>
))}
</div>
)
}
}
export default Content

我不确定您是否要找到发布博客内容并呈现的用户,但我想这将是您的解决方案。

class Content extends React.Component {
state = {
posts: [],
users: []
};
componentDidMount() {
axios
.get("https://jsonplaceholder.typicode.com/posts?_start=10&_limit=10")
.then(resp => resp.data)
.then(data => {
this.setState({ posts: data });
console.log(this.state.posts);
})
.then(
axios
.get("https://jsonplaceholder.typicode.com/users")
.then(resp => resp.data)
.then(data => {
this.setState({ users: data });
console.log(this.state.users);
})
);
}
render() {
return (
<div className="contentContainer">
{this.state.posts.map(post => {
const { userId } = post;
return (
<div className="blogs" key={post.id}>
<div className="blogsPost">
<p className="postTitle">{post.title}</p>
<p className="postbody">{post.body}</p>
</div>
{this.state.users.map(user => {
if (user.id === userId) {
return (
<div key={user.id} className="blogsUsers">
<p>{user.name}</p>
</div>
);
} else {
return null;
}
})}
</div>
);
})}
</div>
);
}
}
export default Content;

最新更新