在next js循环中获取数据

kur*_*ixl 3 javascript reactjs next.js

我正在尝试使用来自 1 个端点的数据来调用按 id 过滤的另一个端点。我计划使用数据获取两个调用getServerSideProps并将数据传递给另一个组件。

第一个调用将返回一个数组,categories然后我尝试循环并获取articles按 id 过滤的数组。

我能够成功取回数组,categories但是当我尝试循环和获取时,articles我得到的值undefined是如何实现这一点?

这是我的一个例子index.js

import ArticleList from "../../components/ArticleList";


const Index = ({ categories, articles }) => {


  return (
    <>
      <ArticleList categories={categories} articles={articles} />
    </>
  )
}

export async function getServerSideProps (context) {
   // console.log('index - getserversideprops() is called')
   try {
     let articles = []
    let response = await fetch('https://example.api/categories')
    const categories = await response.json()

    for (let i = 0; i < categories.results.length; i++) {
      response = await fetch (`https://example.api/articleid/` + categories.results[i].id)
      articles = await response.json()
    }

    console.log(articles,'33')


    if (!categories ) {
        return {
            notFound: true,
        }
    }

    return { 
      props: { 
        categories: categories,
        articles: artices
      }
    }
  } catch (error) {
      console.error('runtime error: ', error)
  }
}

export default Index
Run Code Online (Sandbox Code Playgroud)

这是我的数组的示例console.log(categories.results)

[ {
"id": 2,
"name": "Online"
},
{
"id": 11,
"name": "Retail"
},
{
"id": 14,
"name": "E-Commerce"
}]
Run Code Online (Sandbox Code Playgroud)

我期望articles是 3 个独立的数据数组。如果我将数据传递给另一个组件,这可能吗?如果不是,有什么更好的方法来处理这个问题?

小智 5

尝试Promise.all

export async function getServerSideProps(context) {
  try {
    const categories = await fetch('https://example.api/categories').then((response) => response.json());

    if (!categories) {
      return { notFound: true };
    }

    const articles = await Promise.all(
      categories.results.map((result) =>
        fetch(`https://example.api/articleid/` + result.id).then((response) => response.json())
      )
    );

    const props = { categories, articles };

    return { props };
  } catch (error) {
    console.error('runtime error: ', error);
  }
}
Run Code Online (Sandbox Code Playgroud)

代码会很干净。