reactjs - TypeError:this.state.blog.map 不是函数
问题描述
我试图通过单击它时从数据库 Mongodb atlas 获取数据来显示特定元素的信息,但我收到了这个错误。任何人请帮助我。下面是我的代码。我检查了 console.log typeof response.data 和 response.data
For console.log(response.data); it returns
{_id: "5f116b93de82187214265ea2", username: "Bradd Fox", place: "Chick N' Lamb", dish: "Chicken WIngs", description: "Lorem Ipsum is simply dummy text of the printing a…ldus PageMaker including versions of Lorem Ipsum.", …}
createdAt: "2020-07-17T09:12:51.270Z"
description: "Lorem Ipsum is simply dummy text of the printing and typesetting industry.
dish: "Chicken WIngs"
image: "https://images.unsplash.com/photo-1562967914-608f82629710?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1052&q=80"
place: "Chick N' Lamb"
rating: 4
updatedAt: "2020-07-17T09:12:51.270Z"
username: "Bradd Fox"
__v: 0
_id: "5f116b93de82187214265ea2"
__proto__: Object
console.log(typeof response.data); returns an object.
import React, { Component } from "react";
import Header from "../../components/Header/Header";
import { Container } from "react-bootstrap";
import axios from "axios";
import BlogInfo from "../../components/BlogInfo/BlogInfo";
class Blog extends Component {
state = {
blog: [],
};
componentDidMount() {
axios
.get("http://localhost:3000/blogs/" + this.props.match.params.id)
.then((response) => {
this.setState({
blog: response.data,
});
console.log(response.data);
});
}
render() {
let blogInfo = this.state.blog.map((data) => {
return (
<BlogInfo
key={data._id}
id={data._id}
Name={data.username}
Place={data.place}
Dish={data.dish}
Description={data.description}
Image={data.image}
Rating={data.rating}
/>
);
});
return (
<>
<Header />
<Container className="my-4">{blogInfo}</Container>
</>
);
}
}
export default Blog;
解决方案
Ciao,这个错误意味着this.state.blog
不是数组。尝试像这样修改您的代码:
componentDidMount() {
axios
.get("http://localhost:3000/blogs/" + this.props.match.params.id)
.then((response) => {
let array_response = [response.data];
this.setState({
blog: array_response,
});
console.log(this.state.blog);
});
}
推荐阅读
- wpf - 应用程序资源中断设计器中的事件触发器
- javascript - index.js 的命令
- python-3.x - 如何在 python 中使用位移指定 3GB?
- python - 从 webscrape Python 发出挑选价格
- vue.js - 如何检查冒泡是否触发了vue中的点击?
- python - 如何创建一个程序,用户可以检查菜单上是否有项目?
- r - R 中的 ODBC 连接字符串和/或 DSN
- javascript - 使用 Promise 'catch' 无法捕获 Promise 中引发的错误
- spring-jms - Artemis 中 ActiveMQ 5.x sendFailIfNoSpace 设置的等效项是什么?
- azure - Azure Devops:使用拉取请求构建手动部署到环境