简体   繁体   中英

Can't get getStaticProps to render JSX in Next.JS

I'm trying to render basic data from a locally hosted Strapi API in Next.

The data will successfully log in the console, but I can't manage to map it into JSX.

API get function:

export async function requestQuery(query) {
  const res = await fetch(`${process.env.NEXT_PUBLIC_STRAPI_URL}/${query}`)
  if (res.status !== 200) return [];
  const data = await res.json();
  return data;
}

Index.js file generating static props:

import { requestQuery } from '../lib/staticApi.js';
import Sidebar from '../components/Sidebar.js'

export default function Home({ categories }) {

  return (
    <>
      <Sidebar categories={categories} />
    </>
  )
}

export async function getStaticProps() {

  const categoriesArray = await requestQuery('categories');

  return {
    props: {
      categories: categoriesArray.data
    }
  }
}

Component with successfully passed down props from index.js, but won't render into the HTML:

export default function Sidebar({ categories }) {

  console.group(categories) // successfully logs length 4 array;
  return (
    <ul>
      {/* Just mapping id's to try and get it to work - returns empty list */}
      {categories.map((id) => {
        <li>{id}</li>
      })}
    </ul>
  )
}

Thanks in advance.

You were not returning anything. Check the fixes below. You must either use parentheses or explicitly return something from the map function.

  return (
    <ul>
      {/* Map through array */}
      {categories.map((id) => (
        <li>{id}</li>
      ))}
    </ul>
  )

OR

return (
    <ul>
      {/* Just mapping id's to try and get it to work - returns empty list */}
      {categories.map((id) => {
        // add a return here
        return (<li>{id}</li>);
      })}
    </ul>
  )

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