如何从类别 res.json 中读取和 mab 子数组 useSWR x mongodb x nexjt (node js)

问题描述

这里的任何人都可以帮助我??? 如何在json中读取和映射数组????????

钩子(useSWR/useCategories):

import useSWR from "swr"
const fetcher = (...args) => fetch(...args).then(res => res.json())
function useCategories () {
    
  const { data,error } = useSWR(`/api/categories`,fetcher)
  const sub = data.sub[0]
  
    return {
      categories: data,sub: sub,categoriesLoading: !error && !data,categoriesError: error
    }
  }

  export {useCategories}

页面

const {categories,sub,categoriesLoading } = useCategories()

组件/使用 ?? :

{!categories ? 'Loading' : (<>
        {categories.map(category => (
            <div key={category.slug}>
                name : {category.name}
                sub:{!sub ? '': (<>{sub.map(sub => (<><p key={sub._id}>{sub.name}</p></>))}</>)} 

            </div>
        ))}
        </>)}

先谢谢前辈>.

解决方法

删除

const sub = data.sub[0]

然后:

import {useCategories} from '../useCategories'

export default function pages() {

const {categories,categoriesLoading } = useCategories()

return(<>
{!categories ? 'loading categories..' : (<>
        {categories.map(category => (
            <div key={category.slug}>
                name : {category.name}
                sub: {!category.subs ? 'no sub' : 
               (<>{category.subs.map(sub => (
                <div key={sub._id}>
                sub list : {sub.name}
                </div>
                ))}</>)}

            </div>
        ))}
        </>)}
</>)

}