简体   繁体   中英

Cannot display data in ReactJS. Error: Objects are not valid as a React child. If you meant to render a collection of children, use an array instead

I'm trying to displaying data from my backend, but I'm getting error: Error: Objects are not valid as a React child (found: object with keys {id, price, descr, link, sqf}). If you meant to render a collection of children, use an array instead.

I've been searching for solution and I came across.map but it doesn't work throws again an error.

import React, { useState, useEffect } from 'react';
import ArticleService from '../services/articles';

const Dashboard = () => {
  const [content, setContent] = useState('');

  useEffect(() => {
    ArticleService.articles().then(
      (response) => {
        setContent(response.data);
      },
      (error) => {
        const _content =
          (error.response &&
            error.response.data &&
            error.response.data.message) ||
          error.message ||
          error.toString();

        setContent(_content);
      }
    );
  }, []);

  console.log(content);
  return (
    <div className='container'>
      <h3>{content}</h3>
    </div>
  );
};

export default Dashboard;

console.log of content looks like this: 控制台日志

As you can see, I get content regularly I just can't display it on dashboard page. When I try {content.price} it removes an error but still doesn't show nothing. Any solutions???

According to your log, content is an array of objects so you want to map the array to valid JSX, for example if you want to render in a div element:

<div className="container">
  <h3>
    {content?.map((item) => (
      <div key={item.id}>
        <div>{item.price}</div>
        <div>{item.descr}</div>
      </div>
    ))}
  </h3>
</div>

In addition, the initial state should be an empty array: useState([]) to match the expected data:

const Dashboard = () => {
  const [content, setContent] = useState([]);
  ...
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM