英文:
Hydration problem in Next.js when using the ENV variable for the Image component
问题
遇到了在 Next.js 中与 Strapi 结合使用时关于数据加载的问题。我通过 GraphQL 获取所有数据。Strapi 提供了图像的路径,但没有包含 http:/localhost:/1337。由于这与生产站点不同,我决定创建一个环境变量来解决这个问题。为了将路径解析为完整的图像路径,我创建了以下函数:
interface ImageProp {
data: {
attributes: {
url: string,
}
}
}
export function strapiImage(src: ImageProp) {
return process.env.STRAPIHOST + src.data.attributes.url;
}
最近在浏览器控制台中打开 Next.js 项目时,我开始收到一个错误,但之前没有出现过,我不明白它现在是从哪里来的:
client.js:1 警告:属性 `src` 不匹配。
服务器: "http://localhost:1337/uploads/illustration_cleaning_4c030558a9.svg"
客户端: "undefined/uploads/illustration_cleaning_4c030558a9.svg"
如果我将函数代码中的变量更改为字符串 'localhost:1337',错误就消失了。请问您能告诉我这可能是什么问题,以及如何解决它吗?
英文:
ran into a problem with hydration in Next.js with Strapi. I'm getting all the data through GraphQL. Strapi gives me the paths to the image without http:/localhost:/1337. As this is different from the production site, I decided to make an ENV variable. To parse this to the full image path, I created a function:
interface ImageProp {
data: {
attributes: {
url: string,
}
}
}
export function strapiImage(src: ImageProp) {
return process.env.STRAPIHOST + src.data.attributes.url;
}
In the browser console, when opening the Next.js project recently, I started getting an error. It wasn't there before and I don't understand where it's coming from now:
client.js:1 Warning: Prop `src` did not match.
Server: "http://localhost:1337/uploads/illustration_cleaning_4c030558a9.svg"
Client: "undefined/uploads/illustration_cleaning_4c030558a9.svg"
If I change the variable to the string 'localhost:1337' in the function code, the error disappears. Can you tell me what this could be about and how to solve it?
答案1
得分: 2
为了将变量暴露给浏览器,您必须在变量前加上 NEXT_PUBLIC_
前缀。
尝试将环境更改为 NEXT_PUBLIC_STRAPIHOST
。
英文:
In order to expose a variable to the browser you have to prefix the variable with NEXT_PUBLIC_
Try changing env to NEXT_PUBLIC_STRAPIHOST
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论