Upd*_* XD 5 reactjs server-side-rendering next.js
所以基本上我想在应用程序目录中的客户端组件上使用 getServerSideProps
"use client";
import React, { useLayoutEffect, useState } from "react";
import VoxelDog from "../src/components/loaders/voxel-dog";
import FirstSection from "../src/components/reusable/FirstSection";
import FeaturesSection from "../src/components/reusable/FeaturesSection";
import BannerMobile from "../src/components/mobile/BannerMobile";
// get server side props from the server
const page = (
props: any // get the props from the server
) => {
const [windowWidth, setWindowWidth] = useState(window.innerWidth as number);
useLayoutEffect(() => {
function updateSize() {
setWindowWidth(window.innerWidth);
}
window.addEventListener("resize", updateSize);
updateSize();
return () => window.removeEventListener("resize", updateSize);
}, [windowWidth]);
console.log(props.data);
return (
<>
<div className="flex lg:flex hidden md:hidden md:mt-[60px] lg:mt-[60px] items-center justify-center">
<div
style={{
width: windowWidth > 1300 ? windowWidth / 1.15 : windowWidth / 1.01,
}}
className="flex justify-between px-4 gap-3"
>
<div>
<VoxelDog />
</div>
<div>
<h1 className="text-4xl font-bold text-yellow-300">
Welcome to learn with me
</h1>
<p
className="
text-white
text-lg
font-semibold
tracking-wider
mt-9
lg:max-w-[540px]
md:max-w-[400px]
"
>
Lorem Ipsum is simply dummy text of the printing and typesetting
industry. Lorem Ipsum has been the industry's standard dummy text
ever since the 1500s, when an unknown printer took a galley of
type and scrambled it to make a type specimen book. It has
survived not only five centuries, but also the leap into
electronic typesetting, remaining essentially unchanged. It was
popularised in the 1960s with the release of Letraset sheets
containing Lorem Ipsum passages.
</p>
<button
className="mt-[40px] first-letter:
uppercase bg-yellow-400 text-white font-bold py-3 px-9 rounded-2xl
"
>
Browse different courses
</button>
</div>
</div>
</div>
<div className="block mt-[40px] lg:hidden">
<BannerMobile />
</div>
<div className="block lg:block hidden">
<FirstSection />
<br />
<br />
<FeaturesSection windowWidth={windowWidth} />
</div>
</>
);
};
export async function getServerSideProps(context: any) {
const res = await fetch("http://localhost:3000/api/courses");
const data = await res.json();
return {
props: {
data,
},
};
}
export default page;
Run Code Online (Sandbox Code Playgroud)
如果我在终端和浏览器控制台中控制台记录 props.data,这将返回未定义。我不知道我在这里是否做错了什么。我想要获取的 api 是内部的。
我尝试在服务器组件上使用 getServerSideProps 但它仍然不起作用
小智 5
Next.js 版本 13 中有一项新功能,允许在所有页面(包括应用程序目录)上默认获取服务器端数据。这是通过使用fetch带有cache:'no-store'选项的方法来实现的。这允许服务器端渲染所有页面上的数据,类似于 getServerSideProps 函数的工作原理。您可以参考官方文档https://nextjs.org/blog/next-13#data-fetching了解如何在 Next.js 版本 13 及更高版本中使用此功能。