指南 · 09
SSR、測試與正式環境
伺服器端渲染、hydration、測試,以及可以信賴的清理規則。
伺服器端渲染
Hook 的值會把初始值渲染進伺服器標記,hydration 之後動畫會繼續。React 18 以上版本以 useId 產生穩定的變數名稱;在 React 16 與 17 的伺服器上,請傳入 id。
import { AnimatedProvider } from '@kkwaenggwari/animated';
// The package entry is marked 'use client'. A server layout can render the
// provider directly; hooks and Animated.<tag> go inside Client Components.
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
<AnimatedProvider>{children}</AnimatedProvider>
</body>
</html>
);
}舊版 React 中的穩定 id
只有在以 React 16 或 17 進行伺服器端渲染時才需要。
// React 18+ uses useId automatically. On React 16/17 servers, pass a stable id.
const progress = useAnimatedValue(0, { id: 'hero-progress' });可以信賴的清理
元件擁有的一切都會隨元件一起釋放。
useAnimated、useAnimatedValue、useTimeline與useReorder會在卸載時停止它們的控制器與監聽器。- 在
useAnimated工廠函式中宣告的控制器與輸入,會在相依值改變時一起被取代。 Animated.Keep在動態結束後移除離場的子元素,新的 pose 會從目前位置中斷原本的動態。- 在 React 之外,
bind、bindOutput、createTimeline與createLayoutScene都會回傳明確的dispose。
測試
flushAnimatedUpdates() 會同步套用待處理的輸出,讓確定性的測試可以對 DOM 做斷言。
import { flushAnimatedUpdates } from '@kkwaenggwari/animated';
act(() => progress.setValue(0.5));
flushAnimatedUpdates();
// Pending style writes are applied now; assert on the DOM.文字、屬性與物件屬性
useAnimated 中的 output(target, mapping) 負責 style、屬性、文字或物件屬性的輸出。bindOutput 會立即掛上同樣的對應,並回傳 flush 與 dispose。
const label = useRef(null);
const count = useAnimated(
0,
(value) => {
output(label, { text: new AnimatedComputed([value], (v) => `${Math.round(v * 100)}%`) });
timing(value, { toValue: 1, duration: 1200 });
},
[],
);
<span ref={label} />;