如何解决获取“类型错误:无法使用 Nextjs 读取未定义的属性‘替换’
我正在学习 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组件的代码,在收到的props上使用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 */}
);
}
TIA!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。