Vis*_*rut 8 typescript reactjs next.js next.js13
我正在使用next.js新功能来使用 渲染内容SSR,我正在制作组件,async如下docs所示。
这是我的简单页面组件
export default async function Home() {
const res = await fetch("http://localhost:3000/api/get-quotes");
const quotes = await res.json();
return (
<main className={styles.main}>
<h1>Hello Visrut</h1>
<div>
<span>Total quotes: {quotes.length}</span>
</div>
</main>
)
}
Run Code Online (Sandbox Code Playgroud)
我的应用程序中有authenticated和non-authenticated路线,我正在做什么将它们分开_app.tsx
// _app.tsx
interface AppProps {
Component: React.ElementType;
pageProps: Record<string, unknown>;
}
const App: React.FC<AppProps> = ({ Component, pageProps }) => {
const router = useRouter();
if (router.pathname.includes("home")) {
return <Home />; // Error: 'Home' can't be used as a JSX component, Its return type Promise<Home> is not a valid JSX component.
}
return (
<AuthContextProvider>
<Navbar />
<Head />
<Component {...pageProps} />
<Footer />
</AuthContextProvider>
)
};
export default App;
Run Code Online (Sandbox Code Playgroud)
我想渲染Home不需要身份验证的组件,似乎我也因为async关键字的原因而不能直接将其作为子组件。
async当我直接将组件渲染到其他正常组件中时,我也在浏览器上收到此错误next.js
Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.
Run Code Online (Sandbox Code Playgroud)
khe*_*dev 18
将异步代码移至getServerSideProps函数中,并将响应Home作为 Props 传递到组件中
参考:https ://nextjs.org/docs/basic-features/data-fetching/get-server-side-props
export async function getServerSideProps() {
const res = await fetch("http://localhost:3000/api/get-quotes");
const quotes = await res.json();
return {
props: {
quotes: quotes,
}, // will be passed to the page component as props
};
}
Run Code Online (Sandbox Code Playgroud)
export default function Home({quotes}) {
return (
<main className={styles.main}>
<h1>Hello Visrut</h1>
<div>
<span>Total quotes: {quotes.length}</span>
</div>
</main>
)
}
Run Code Online (Sandbox Code Playgroud)
import { use } from "react";
async function getQuotes() {
return await fetch("http://localhost:3000/api/get-quotes", {
cache: "no-store",
}).json();
}
export default function Home() {
const quotes = use(getQuotes());
return (
<main className={styles.main}>
<h1>Hello Visrut</h1>
<div>
<span>Total quotes: {quotes.length}</span>
</div>
</main>
);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19587 次 |
| 最近记录: |