【问题标题】:Dynamic route not detecting change in API response on page change动态路由未检测到页面更改时 API 响应的更改
【发布时间】:2021-04-16 23:56:59
【问题描述】:

我对 Svelte/Sapper 很陌生,所以请多多包涵。我有一个从 API url 获取的动态路由,并且根据“捆绑包”它应该呈现不同的组件。该路由在加载或刷新时工作正常,但在页面之间单击时,它不会检测到“捆绑”并尝试加载错误的组件:

[...slug].svelte

<script context="module">
    export async function preload({ params }) {
        const res = await this.fetch(process.env.SVELTE_APP_API_URL + '/alias?_format=json&slug='+ params.slug);
        if (res.status === 200) {
            const data = await res.json();
            return { node: data };
        } else {
            this.error(res.status, data.message);
        }
    }
</script>


<script>
    import Article from '../bundles/Article.svelte';
    import Page from '../bundles/Page.svelte';
    import CustomPage from '../bundles/CustomPage.svelte';
    import Error from './_error.svelte';

    export let node;

    const bundles = {
        article: Article,
        page: Page,
        custom_page: CustomPage
    };
    let Component;
    let status = '';
    let error = {
        message: ''
    };


    if(bundles[node.bundle]){
        Component = bundles[node.bundle];
    }else{
        Component = Error;
        status = '404';
        error.message = 'Page not found';
    }

</script>


{node.bundle} // This is correct!

{#key [node.bundle]}
<svelte:component node={node} status={status} error={error} this={Component}/>
{/key}. // This is incorrect!

但它确实获取了正确的数据 - 如果我在两个不同的“页面”包之间单击它会呈现正确的内容。

如果我的处理方式完全错误,请告诉我:)

【问题讨论】:

    标签: svelte sapper


    【解决方案1】:

    我发现我必须让组件变量反应:

    $: component = bundles[node.bundle];
    

    【讨论】:

      猜你喜欢
      • 2020-02-01
      • 2012-10-12
      • 1970-01-01
      • 2019-02-16
      • 2016-09-01
      • 2017-02-16
      • 2020-07-02
      • 2021-01-13
      • 2021-12-22
      相关资源
      最近更新 更多