首页 > 解决方案 > 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;

标签: reactjsaxios

解决方案


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);
  });
 }

推荐阅读