简体   繁体   English

Sveltekit - 如何在子组件的脚本标签中访问“反应式上下文”(通过上下文传递的存储)?

[英]Sveltekit - How to access a "reactive context" (a store passed down via context) in the Script tag of Child Component?

I'm initialising a Class in the onMount function of a Parent Wrapper component and want to expose it to all the children.我正在父包装器组件的 onMount function 中初始化 Class 并希望将其公开给所有子级。 I'm currently using a writable store that I set to the Class in the onMount function.我目前正在使用我在onMount function 中设置为 Class 的可写存储。

let classA;
        
let classStore = writable(classA);
        
setContext('classContext', classStore);
    
onMount(async () => {
    const module = await import('library');
    const ClassInQuestion = module.default;
    
    classA = new ClassInQuestion()
    
    classStore.set(classA)
})

In a child component I'd try accessing the context like so:在子组件中,我会尝试像这样访问上下文:

const myContext = getContext('classContext');
console.log($myContext) //expected: class

What I get is undefined until I re-render the component.在我重新渲染组件之前,我得到的是未定义的。

I replicated a simplified version of the problem in this Stackblitz .我在这个 Stackblitz中复制了问题的简化版本。 As you can see the context gets called correctly with getContext , but in the <script> tag the old value is still being logged.如您所见,使用getContext正确调用了上下文,但在<script>标记中仍记录旧值。 Calling getContext in onMount doesn't work either.onMount中调用getContext也不起作用。 I want to access the Instance of the class and ideally update it from a child component.我想访问 class 的实例并理想地从子组件更新它。

In your child component, you could make myContext reactive so it triggers on every change在您的子组件中,您可以使myContext具有反应性,以便在每次更改时触发

const myContext = getContext('testContext');
$: if(myContext) console.log($myContext);

The output is: output 是:

在此处输入图像描述

At this point we dont know if the child is mounted and perhaps you dont want to trigger anything before mount .此时我们不知道孩子是否已挂载,也许您不想before mount触发任何内容。 Therefore, we can add further conditions eg waiting for the childs mount or checking a condition of myContext :因此,我们可以添加更多条件,例如等待子挂载或检查myContext的条件:

let mounted = false;
const myContext = getContext('testContext');

$: if(myContext && mounted && $myContext == "after mount") contextReady();

async function contextReady() {
    console.log($myContext)
}
    
onMount(() => {
    mounted = true;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM