ReactJS - 映射不适用于单个项目



我有一个关于map函数的非常琐碎的问题。我正在向我的API发出一个请求,返回单个对象。然后我想在渲染方法中显示对象。

const api = axios.create({
baseURL: `https://localhost:5001/api/v1/`
})
class SinglePost extends Component {
state = {
post: []
}
constructor(props) {
super(props);
api.get(`posts/9a6b5be6-b3ef-4c2d-a36b-08da14c62914`).then(res => {
console.log(res.data)
this.setState({ posts: res.data })
})
}
render() {
return (
<div>
{
this.state.post.map(x => <h2>{x.title}</h2>)
}
</div>
)
}
}
export default SinglePost;

res.data的console.log()似乎可以很好地显示数据。

{
"id": "9a6b5be6-b3ef-4c2d-a36b-08da14c62914",
"name": null,
"title": "Teeest",
"urlTitle": null,
"content": "123",
"created": "2022-04-02T18:30:55.1536762",
"description": "123",
"score": 0,
"isDeleted": false,
"currentFlagStatus": 0,
"flagReason": null,
"userId": "9ecac069-8cfc-4cac-8056-87093fb9c57c",
"authorName": null,
"authorProfilePic": null,
"hashtags": [
{
"id": "a8bc782c-7f5e-4dfc-220c-08da1355d3ec",
"hashtagName": "byq",
"hashtagNameInLower": "byq",
"amountOfHashtagFollowers": 0
},
{
"id": "a5efd6b1-cff0-40b5-2218-08da1355d3ec",
"hashtagName": "Test",
"hashtagNameInLower": "test",
"amountOfHashtagFollowers": 0
}
],
"comments": []
}

然而,我的map函数似乎没有将数据放入<h2>标记中。将断点设置为this.state.post.map(x => <h2>{x.title}</h2>)表明它甚至没有被命中,但是控制台上没有错误。如何正确绘制此地图?

编辑:

正如Alon Barenboim和Nicholas Tower指出的那样,有一个拼写错误(将状态设置为帖子而不是帖子(。然而,现在的问题是,这段代码现在抛出了this.state.post.map is not a function的错误。

我想问题是您为posts调用this.setState({ posts: res.data }),但试图映射post:this.state.post.map(x => <h2>{x.title}</h2>

编辑:

如果我理解正确,您只需要在组件中显示存储在posts对象内的数据。为了做到这一点,您只需执行以下操作:

const api = axios.create({
baseURL: `https://localhost:5001/api/v1/`
})
class SinglePost extends Component {
state = {
posts: []
}
constructor(props) {
super(props);
api.get(`posts/9a6b5be6-b3ef-4c2d-a36b-08da14c62914`).then(res => {
console.log(res.data)
this.setState({ posts: res.data })
})
}
render() {
return (
<div>
{this.state.posts ? <h2>this.state.posts.title</h2> : null}
</div>
)
}
}
export default SinglePost;

只需写入{this.state.posts.ATTRIBUTE},就可以获得存储在状态对象内的每个值

最新更新