子组件中获取的数据在页面更改时不会更新

huangapple go评论53阅读模式
英文:

Fetched data in child component does not update on page change

问题

以下是代码部分的翻译:

I have a page:
src/routes/[pageid]/+page.svelte
and a file
src/routes/[pageid]/page.js

The page.js fetches data from an API and shows correctly on +page.svelte.

Inside +page.svelte I have another component src/components/pagesection.svelte

The [pageid]/+page.svelte page loops over that PageSection component and passes the {section} as a data attribute.

When I change the page (which is dynamic). The {section} in the child component does not update.

以下是 +page.svelte 的翻译:

import PageSection from '../../components/PageSection.svelte';

export let data;
$: ({pageData} = data);

{#if pageData}
  <h1>{pageData[0].attributes.Title}</h1>

  {#each pageData[0].attributes.sections.data as section}
    <!-- this updates here -->
    <h4>Section ID: {section.id}</h4>

    <!-- but not in here-->
    <PageSection data={section} />
  {/each}
{/if}

以下是 PageSection.svelte 的翻译:

import { onMount } from 'svelte';
import { ApiUrl } from '../stores.js';

export let data;

let SectionID = data.id;
const SectionApiURL = `${ApiUrl}/api/sections/${SectionID}?populate=article`;
let sectionDetails;

onMount(() => {
  fetch(SectionApiURL)
    .then(response => {
      if (response.ok) {
        return response.json();
      } else {
        throw new Error('Network response was not ok.');
      }
    })
    .then(data => {
      sectionDetails = data;
    })
    .catch(error => {
      console.error('There was a problem fetching the page data:', error);
    });
});

希望这能帮助您解决问题。

英文:

I have a page:
src/routes/[pageid]/+page.svelte
and a file
src/routes/[pageid]/page.js

The page.js fetches data from an API and shows correctly on +page.svelte.

Inside +page.svelte I have another component src/components/pagesection.svelte

The [pageid]/+page.svelte page loops over that PageSection component and passes the {section} as a data attribute.

When I change the page (which is dynamic). The {section} in the child component does not update.

+page.svelte

import PageSection from &#39;../../components/PageSection.svelte&#39;;

export let data;
$: ({pageData} = data);


{#if pageData}

  &lt;h1&gt;{pageData[0].attributes.Title}&lt;/h1&gt;

  {#each pageData[0].attributes.sections.data as section}
    &lt;!-- this updates here --&gt;
    &lt;h4&gt;Section ID: {section.id}&lt;/h4&gt;

    &lt;!-- but not in here--&gt;
    &lt;PageSection data={section} /&gt;
  {/each}

{/if}

PageSection.svelte

import { onMount } from &#39;svelte&#39;;
import {ApiUrl} from &#39;../stores.js&#39;;

export let data;

let SectionID = data.id;
const SectionApiURL = `${ApiUrl}/api/sections/${SectionID}populate=article`;
let sectionDetails;

onMount(() =&gt; {
  fetch(SectionApiURL)
  .then(response =&gt; {
       if (response.ok) {
          return response.json();
       } else {
          throw new Error(&#39;Network response was not ok.&#39;);
       }
     })
     .then(data =&gt; {
          sectionDetails = data;
      })
     .catch(error =&gt; {
        console.error(&#39;There was a problem fetching the page data:&#39;,error);
  });
});

Any help would be so appreciated. This seems like it should be such a basic thing to do for any website but I have spent hours trying to find out how to get the page information to change inside the component.

Thank you in advance

答案1

得分: 0

你的问题是,在PageSection组件内,只有在组件最初挂载时才获取部分详细信息,而实际上你想在data属性更新时获取部分详细信息。

你可以很容易修复这个问题(同时,也有机会切换到更现代的async/await语法):

import { ApiUrl } from '../stores.js';
export let data;

$: sectionDetails = updateSection(data) // 每当data更新时都会运行

async function updateSection(section) {
  try {
    const response = await fetch(`${ApiUrl}/api/sections/${section.id}?populate=article`);
    if (!response.ok) {
      throw an Error('网络响应不正常。');
    }
    return response.json();
  } catch (error) {
    console.error('获取页面数据时出现问题:', error);
  }
}
英文:

Your issue is that, inside the PageSection component, you only fetch section details when the component is initially mounted, when what you really want to do is fetch section details whenever the data prop updates.

You can easily fix this (also, took the opportunity to switch to a more modern async/await syntax):

import { ApiUrl } from &#39;../stores.js&#39;;
export let data;

$: sectionDetails = updateSection(data) // will run whenever data updates

async function updateSection(section) {
  try {
    const response = await fetch(`${ApiUrl}/api/sections/${section.id}?populate=article`);
    if (!response.ok) {
      throw new Error(&#39;Network response was not ok.&#39;);
    }
    return response.json();
  } catch (error) {
    console.error(&#39;There was a problem fetching the page data:&#39;, error);
  }
}

huangapple
  • 本文由 发表于 2023年3月4日 07:28:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/75632674.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定