mirror of
https://github.com/farion1231/cc-switch.git
synced 2026-07-24 21:30:17 +08:00
1be9c56ec5
Two bugs were caused by ref synchronization race condition in commit 7d495aa:
- EditProviderDialog: provider prop was null on first render
- UsageScriptModal: conditional render guard was false on first click
Root cause: useEffect updates ref asynchronously, but render happens before
effect runs. On first click, ref is still null causing components to fail.
Solution: Create useLastValidValue hook that updates ref synchronously during
render phase instead of in useEffect. This ensures ref is always in sync with
state, eliminating the race condition.
Changes:
- Add useLastValidValue hook for preserving last valid value during animations
- Replace manual ref + useEffect pattern with the new hook
- Remove non-null assertions (!) that were needed as workaround
21 lines
543 B
TypeScript
21 lines
543 B
TypeScript
import { useRef } from "react";
|
|
|
|
/**
|
|
* 保存最后一个非 null/undefined 的值
|
|
* 用于 Dialog 关闭动画期间保持内容显示
|
|
*
|
|
* @param value 当前值
|
|
* @returns 当前值(如果有效)或最后一个有效值
|
|
*/
|
|
export function useLastValidValue<T>(value: T | null | undefined): T | null {
|
|
const ref = useRef<T | null>(null);
|
|
|
|
// 同步更新 ref(在渲染期间,不在 useEffect 中)
|
|
if (value != null) {
|
|
ref.current = value;
|
|
}
|
|
|
|
// 返回当前值或最后有效值
|
|
return value ?? ref.current;
|
|
}
|