简体   繁体   中英

trying to use crawled data but error appears like 'Objects are not valid as a React child (found: [object Promise])'

I want to print out the crawled data from the site I want using Gatsby. But I don't know why this error appears.

here's my crawler

class Crawler {
  constructor() {
    this.client = axios.create();
  }

  async crawlNews() {
    const url = 'https://finance.naver.com/news/news_list.naver?mode=RANK';
    const settedResult = await this.client
        .get(url, { responseType: 'arraybuffer' })
        .then((response) => {
            const setResult = [];
            const content = iconv.decode(response.data, 'EUC-KR');
            const $ = cheerio.load(content);
            $('.simpleNewsList > li').each((i, el) => {
                const title = $(el).text();
                setResult.push({
                    id: parseInt(i) + 1,
                    title: title
                        .replace(/(\r\n|\n|\r|\t)/gm, '')
                        .toString(),
                });
            });

            return setResult;
        })
        .catch((err) => console.error(err));
    return settedResult;
}

}

and here's Slide component

import React from 'react';

export function Slide(props) {
  const { index, title } = props;
  return (
    <div>
      {index} | {title}
    </div>
  );
}

here's pages/index.js in gatsby

async function Home() {
  const settedResult = new Crawler();
  const dataSource = await settedResult.crawlNews();
  const result = dataSource.map((obj) => {
    <Slide index={obj.id} title={obj.title} />;
  });

  return <div>{result}</div>;
}

export default Home;

When I run 'gatsby develop' with the above files, an error like the title appears

Maybe you can provide a stackblitz? Its seems you'r missing a return here:

    const result = dataSource.map((obj) => {
      <Slide index={obj.id} title={obj.title} />;
    });

This should work

  const result = dataSource.map((obj) => 
    <Slide index={obj.id} title={obj.title} />
  );

or

  const result = dataSource.map((obj) => {
      return <Slide index={obj.id} title={obj.title} />;
  };

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