首页 > 解决方案 > Sapper/Svelte 在另一个组件完成发布后更新组件内的状态

问题描述

我知道这个问答,但仍然无法在我的情况下应用它。

我正在使用工兵并有两个组件。Component2 是为菜单创建选项或类别。Component1 显示带有创建的所有选项/类别的菜单。此外,component1 在其主体中包含 component2。

我的问题是当我使用 component1 并点击保存时,一切正常(输入数据保存到 db)现在 component1 需要反映刚刚创建的新选项/类别,但它不知道更改。单击组件2中的保存后,如何使组件1(显示所有类别)知道更改/更新/新类别?

Component2 代码:createcategoy.js 工作正常并将数据发布到我的数据库,所以这不是问题。

<script>
...code to get locationid unrelated to my issue

function createcategory(event){
  let categoryorder = event.target.categoryorder.value
  let categoryname = event.target.categoryname.value
  let categorydescription= 
   event.target.categorydescription.value

 
  fetch('createCategory', {
  method: 'POST',
  credentials : 'include',
  headers: {
  'Accept': 'application/json',
  'Content-type' : 'application/json'
  },
  body: JSON.stringify({
  
  location_id : locationid,
  category_order : categoryorder,
  category_name : categoryname,
  category_description :categorydescription
  })
  }).then(response => response.json())
  .then(responseJson => {
  console.log("All Is Well. Category created 
      successfully")
  })
  .catch(error => console.log(error));

  
  }

</script>
html form...

现在这里是显示位置的组件 1,每个位置都有自己的由组件 2 创建的类别:

  <script>     
     import { onMount } from 'svelte';
     import { goto } from '@sapper/app';
     import Createcategory from './createCategory.svelte'

     let locations = []
     onMount(async () => {

     fetch('menubuilder', {
     method: 'POST',
     credentials : 'include',
     headers: {
     'Accept': 'application/json',
     'Content-type' : 'application/json'
     },
     body: JSON.stringify({

     })
     }).then(response => response.json())
     .then(responseJson => {
     locations = responseJson.info
     })
     .catch(error => console.log(error));

     }) //onMount fn
   
   </script>  

    <h1> Menu Builder </h1>
         
    <dl>
    
      {#each locations as location}

  
       
        <br>
    <h1>{location.locationname} </h1>
        <p>{location._id} </p>
          

   <!-- This is component2 where I use to create new 
      category-->
  <Createcategory locationname= 
  {location.locationname} locationid={location._id}/>
  </dt>
  
  
  <dd> 
            
     {#each location.locationcategories as item}
     <div >       
       <p>{item.categoryname} </p>: 
       {item.categorydescription}
       
     </div>
     {/each}
      
        
  
  {/each}

</dl>

现在,我唯一的难题是工兵/苗条状态如何运作。当我提交创建类别的 component2 时,如何让 component1 更新它是 state/dom。

我阅读了文档中的反应性部分,位置变量在 component1 内部分配,但 component2 是负责创建新类别的变量。

那么,当component2将类别保存到db时,我应该如何更新component1(位置变量及其dom)?

标签: sappersvelte-3

解决方案


有两种常见的方法可以做到这一点:

  1. 在发布新类别后引发事件,您的新工作流程将类似于:

Component2 推送到服务器
Component2 引发一个事件categoryAdded,并将该类别作为有效负载。Component1 通过将给定类别附加到它的数组来对此事件作出反应。

或者,我认为更好的方法:

  1. 在两个组件之外的商店中添加您的类别。

Component1 将简单地显示商店的内容。
Component2 会将新商品推送到商店。

存储本身将负责从服务器获取/推送数据。这有两个额外的好处:

  • 组件只关心显示类别,并不关心它们来自哪里或去哪里。
  • 您可以轻松更改类别的存储方式,它使用哪个端点,...

推荐阅读