DEV Community

Kenji Suzuki
Kenji Suzuki

Posted on

state_referenced_locally

2025-03-17

svelte@5.22.1で$drrived.byの戻り値を直接展開すると、checkタスクでwarningが出るようになった

Warn: State referenced in its own scope will never update. Did you mean to reference it inside a closure? https://svelte.dev/e/state_referenced_locally (svelte) topHeight: number; totalHeight: number; visibleKeys: T[]; 
Enter fullscreen mode Exit fullscreen mode

以下のようなコード

 let { topHeight, totalHeight, visibleKeys } = $derived.by<{ topHeight: number; totalHeight: number; visibleKeys: T[]; }>(() => { if (!itemsRect) { return { topHeight: 0, totalHeight: 0, visibleKeys: [] }; } const itemsY = Math.max(0, itemsRect.y * -1); const visibleBottomY = itemsY + document.documentElement.clientHeight; const getItemHeight = (key: T) => { return heightMap[key] ?? itemMinHeight; }; const startRow = (() => { let sumHeight = 0; for (const [i, key] of keys.entries()) { sumHeight += getItemHeight(key) + gap; if (sumHeight > itemsY) { return Math.max(0, i - overScanCount); } } return 0; })(); const topHeight = keys.slice(0, startRow).reduce((p, v) => { return p + getItemHeight(v) + gap; }, 0); const endRow = (() => { let sumHeight = topHeight; for (const [i, item] of keys.slice(startRow).entries()) { sumHeight += getItemHeight(item) + gap; if (sumHeight >= visibleBottomY) { return i + startRow + overScanCount; } } return keys.length - 1; })(); const totalHeight = Math.ceil( keys.reduce((p, v) => { return p + getItemHeight(v); }, 0) + (keys.length - 1) * gap, ); const visibleKeys = keys.slice(startRow, endRow + 1); return { topHeight, totalHeight, visibleKeys, }; }); 
Enter fullscreen mode Exit fullscreen mode

とりあえず展開しないように修正

Top comments (0)