MST

星途 面试题库

面试题:Svelte响应式变量在复杂组件结构中的状态管理

假设你有一个多层嵌套的Svelte组件结构,顶层组件需要与深层子组件共享并管理一个响应式变量的状态,且该变量状态的变化需要在多个中间层组件触发不同的副作用操作,描述你会如何设计状态管理方案,并编写核心代码示例。
48.7万 热度难度
前端开发Svelte

知识考点

AI 面试

面试题答案

一键面试
  1. 状态管理方案设计
    • 使用Svelte的上下文(Context API)来在组件树中共享状态。顶层组件将状态和更新状态的函数通过setContext传递下去,深层子组件和中间层组件通过getContext获取。
    • 中间层组件可以在状态变化时,利用$: 语句来触发副作用操作。
  2. 核心代码示例
    • 顶层组件(App.svelte)
<script>
    import { setContext } from'svelte';
    import MiddleComponent from './MiddleComponent.svelte';
    let sharedValue = 0;
    const updateSharedValue = (newValue) => {
        sharedValue = newValue;
    };
    setContext('sharedContext', {
        sharedValue,
        updateSharedValue
    });
</script>

<MiddleComponent />
  • 中间层组件(MiddleComponent.svelte)
<script>
    import { getContext } from'svelte';
    import DeepComponent from './DeepComponent.svelte';
    const { sharedValue, updateSharedValue } = getContext('sharedContext');
    $: {
        // 这里可以触发与sharedValue变化相关的副作用操作
        console.log('Shared value in middle component has changed to:', sharedValue);
    }
</script>

<DeepComponent />
  • 深层子组件(DeepComponent.svelte)
<script>
    import { getContext } from'svelte';
    const { sharedValue, updateSharedValue } = getContext('sharedContext');
</script>

<button on:click={() => updateSharedValue(sharedValue + 1)}>Increment Shared Value</button>
<p>The shared value is: {sharedValue}</p>