【发布时间】:2021-01-17 12:51:50
【问题描述】:
我知道this q&a,但仍然无法在我的情况下应用它。
我正在使用工兵并有两个组件。 Component2 是为菜单创建选项或类别。 Component1 显示包含所有创建的选项/类别的菜单。此外,component1 在其主体中包含 component2。
我的问题是当我使用 component1 并点击保存时,一切正常(输入数据保存到 db)现在 component1 需要反映刚刚创建的新选项/类别,但它不知道更改。在组件 2 中单击保存后,如何让组件 1(显示所有类别)知道更改/更新/新类别?
组件2代码: 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)?
【问题讨论】: