gpt4 book ai didi

server-side-rendering - 在 Sveltekit 上获取上下文 ="module"中的页面参数

转载 作者:行者123 更新时间:2023-12-05 03:28:40 30 4
gpt4 key购买 nike

如何在 context="module" 和使用 {#await load()} block 中访问页面参数 ?

如果我使用{#await load()} block 我不会收到错误并且页面正常工作,但如果我使用Await阻止我得到这个错误:

*无法读取未定义的属性(读取“params”)*

(I have to mention that I can see the result of console.log in scripttag)
(I'm using Await block to load a spinner before completingthe content load)

这是代码:

<script context="module">
import { gql, GraphQLClient } from 'graphql-request';

export async function load(ctx) {
const pageSlug = await ctx.params.slug;
const graphcms = new GraphQLClient(import.meta.env.VITE_GRAPHCMS_URL, {
headers: {}
});

const getArticleQuery = gql`
query getArticle {
articles(filters: { Slug: { eq: "${pageSlug}" } }) {
data {
id
attributes {
Title
Slug
Content
FeaturedImage {
data {
attributes {
url
}
}
}
}
}
}
}
`;

const data = await graphcms.request(getArticleQuery);

if (data) {
return {
props: {
article: data.articles.data[0],
pageSlug: pageSlug
}
};
} else {
throw new Error(data);
}
}
</script>

<script>
import { Jumper } from 'svelte-loading-spinners';
export let article;
export let pageSlug;
$: console.log('pageSlug', pageSlug);
</script>

{#await load()}
<div class="flex justify-center items-center">
<Jumper size="60" color="#FF3E00" unit="px" duration="1s" />
</div>
{:then data}
<span>{article.attributes.Title}</span>
<span>{JSON.stringify(pageSlug)}</span>
{:catch error}
<p style="color: red">{error.message}</p>
{/await}

最佳答案

这不是 load 的工作方式。

load 函数在页面挂载之前运行,并将生成的 props 传递给页面。它将在您访问的第一个页面的服务器上运行,并在所有后续页面的客户端上运行。

如果您绝对需要在显示内容之前有一个加载微调器,则必须在客户端加载数据并单独加载客户端。这可以通过在 onMount 函数中加载数据来完成,但是您失去了服务器端呈现的好处。

关于server-side-rendering - 在 Sveltekit 上获取上下文 ="module"中的页面参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71198957/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com