1

我正在学习 Nextjs。尝试从动态页面中的 firestore 获取数据时出现此错误 ~“[].js”。

replace 是一种用于转换下面使用的 EventLogistics 组件中的地址属性的方法。

    import { getAllEvents, getEventById } from "../../../helpers/api-util.js"

function EventDetailPage(props) {
  const { event } = props;

  if (!event) {
    return (
      <ErrorAlert>
        <p>No event found</p>
      </ErrorAlert>
    );
  }

  return (
    <Fragment>
      <EventSummary title={event.title} />
      <EventLogistics
        key={event.id}
        date={event.date}
        address={event.location}
        image={event.image}
        imageAlt={event.title}
      />
      <EventContent>
        <p>{event.description}</p>
      </EventContent>
    </Fragment>
  );
}

export async function getStaticProps(context) {
  const eventId = context.params.eventId;
  console.log(eventId);
  const event = await getEventById(eventId);
  return {
    props: {
      event: event,
    },
    revalidate: 3600,
  };
}

export async function getStaticPaths() {
  const events = await getAllEvents();
  const paths = events.map((event) => ({ params: { eventId: event.id } }));
  return {
    paths: paths,
    fallback: 'blocking',
  };
}

在 api-util.js 中。我有几个辅助函数来获取数据。下面是代码。好心的帮助

export async function getAllEvents() {
  const response = await fetch(
    "https://next-events-4a68f-default-rtdb.firebaseio.com/events.json"
  );
  const data = await response.json();
  const events = [];
  for (const key in data) {
    events.push({
      id: key,
      ...data[key]
    });
  }
  return events;
}

export async function getFeaturedEvents() {
    const events = await getAllEvents();
  return events.filter((event) => event.isFeatured);
}

export async function getEventById(id) {
  const allEvents = await getAllEvents();
  return allEvents.filter((event) => event.id === id);
}`
  

下面是 EventLogistics 组件的代码,其中在收到的道具上使用了 replace 方法

export default function EventLogistics(props) {
  const { date, address, image, imageAlt } = props;

  const humanReadableDate = new Date(date).toLocaleDateString('en-US', {
    day: 'numeric',
    month: 'long',
    year: 'numeric',
  });
  const addressText = address.replace(', ', '\n');

  return (
    {/* renders a card with the props above */}
  );
}

蒂亚!

4

0 回答 0