我 console.log 数据并显示在控制台上。但它没有在浏览器上显示数据。它说 events.map 不是函数

I console.log the data and it display on console. But it didn't display the data on the browser. It's saying events.map is not a function

import Layout from '@/components/Layout';
import { API_URL } from '@/config/index';

export default function HomePage({ events }) {

  return (
    <Layout>

      <h1>Upcoming Events</h1>

      {events.length === 0 && <h3>No events to show</h3>}

      {events.map((evt) => (
        <h3 key={evt.id}>{evt.name} </h3>
      ))}

    </Layout>
  );
}

export async function getStaticProps() {

  const res = await fetch(`${API_URL}/api/events`);

  const events = await res.json();

  return {
    props: { events },
    revalidate: 1,
  };
}

events最初可以是undefined。就是这个问题。

定义事件的默认值

export default function HomePage({ events = [] }) { ...

并尝试使用三元运算符

{
    events.length === 0 ? (
        <h3>No events to show</h3>
    ) : (
        events.map(evt => <h3 key={evt.id}>{evt.name} </h3>)
    );
}

或检查事件是否是 array

     {events.length === 0 && <h3>No events to show</h3>}

      {Array.isArray(events) && events.map((evt) => (
        <h3 key={evt.id}>{evt.name} </h3>
      ))}