面试题答案
一键面试1. 使用 Svelte stores 管理状态
- 创建 store:在 Svelte 中,通过
import { writable } from'svelte/store';
来创建可写的 store。例如,创建一个用于存储路由参数相关状态的 store:
import { writable } from'svelte/store';
export const routeParamStore = writable(null);
- 订阅 store:在组件中订阅该 store,以便在状态变化时更新组件。
import { routeParamStore } from './stores.js';
let paramValue;
const unsubscribe = routeParamStore.subscribe((value) => {
paramValue = value;
});
$: onDestroy(() => {
unsubscribe();
});
2. 路由参数与 store 的关联
- 获取路由参数:在 Svelte 应用中,通常使用
$page.params
获取路由参数(假设使用 SvelteKit)。例如,在一个页面组件中:
<script context="module">
export function load({ params }) {
return {
param: params.id
};
}
</script>
<script>
import { routeParamStore } from './stores.js';
export let param;
$: routeParamStore.set(param);
</script>
这样,当路由参数变化时,会更新 routeParamStore
。
3. 避免不必要的重新渲染
- 细粒度更新:确保组件只在实际依赖的状态变化时重新渲染。例如,如果你有一个展示部分依赖于路由参数,将这部分逻辑封装在一个独立组件中,该组件只订阅相关的 store。
// 子组件
<script>
import { routeParamStore } from './stores.js';
let paramValue;
const unsubscribe = routeParamStore.subscribe((value) => {
paramValue = value;
});
$: onDestroy(() => {
unsubscribe();
});
</script>
{#if paramValue}
<p>展示基于路由参数的值: {paramValue}</p>
{/if}
- 使用
$: $
语法:Svelte 的$: $
语法可以在依赖的值变化时触发副作用,且不会导致整个组件重新渲染。例如:
import { routeParamStore } from './stores.js';
let derivedValue;
$: $routeParamStore.then((param) => {
// 基于路由参数计算派生值
derivedValue = param * 2;
});
4. 处理依赖关系
- 双向依赖:如果路由参数与其他状态存在双向依赖,可以通过
update
方法更新 store 来触发相关的更新逻辑。例如,假设另一个 storeotherStore
依赖于路由参数,当otherStore
变化时也可能影响路由参数相关状态。
import { writable } from'svelte/store';
export const otherStore = writable(null);
export const routeParamStore = writable(null);
// 当 otherStore 变化时更新 routeParamStore
otherStore.subscribe((value) => {
if (value) {
routeParamStore.update((param) => {
// 根据 otherStore 的值更新路由参数相关状态
return param + value;
});
}
});
- 派生状态:对于由路由参数派生出来的状态,可以使用
derived
store。例如:
import { writable, derived } from'svelte/store';
const routeParamStore = writable(null);
const derivedStore = derived(routeParamStore, ($param) => {
return $param? `派生值: ${$param}` : null;
});
这样,当 routeParamStore
变化时,derivedStore
会自动更新,且不会导致不必要的重新渲染。通过以上方式,可以有效地将动态路由参数传递与状态管理进行优化结合,提高大型 Svelte 应用的性能、可维护性和可扩展性。