use*_*513 2 javascript reactjs next.js
我正在尝试发送一些关于hosted url(部署我的构建的地方)的基本文本。但是我收到了这个错误
ReferenceError: location is not defined
here is my code
https://codesandbox.io/s/laughing-mendel-pf54l?file=/pages/index.js
export const getStaticProps = async ({ preview = false, previewData = {} }) => {
return {
revalidate: 200,
props: {
//req.host
name: location.hostname == "www.google.com" ? "Hello" : "ccccc"
}
};
};
Run Code Online (Sandbox Code Playgroud)
你能显示你的进口,因为这可能是你从进口路由器 'next/client'
假设您正在使用基于功能的组件
您需要按如下方式导入路由器:
import {useRouter} from "next/router";
Run Code Online (Sandbox Code Playgroud)
在你的函数体中:
const router = useRouter();
Run Code Online (Sandbox Code Playgroud)
getStaticProps()在 Node.js 中构建时执行,它没有location全局对象 \xe2\x80\x93Location是浏览器 API 的一部分。此外,由于代码是在构建时执行的,因此 URL 尚不清楚。
getStaticProps为getServerSideProps(请参阅文档)。这意味着该函数在运行时针对每个请求单独调用。context传递给 的对象中getServerSideProps,取出 Node.jshttp.IncomingMessage对象。Host标题。export const getServerSideProps = async ({ req }) => {\n return {\n props: {\n name: req.headers.host === "www.google.com" ? "Hello" : "ccccc"\n }\n };\n};\nRun Code Online (Sandbox Code Playgroud)\n笔记:
\n==为===,因为通常建议使用后者。由于静默类型转换,前者可能会产生一些意外的结果。revalidate,因为这不适用于getServerSideProps().| 归档时间: |
|
| 查看次数: |
2976 次 |
| 最近记录: |