arco-design / arco-design-mobile

React mobile UI components library based on Arco Design
https://arco.design/mobile/react/arco-design/pc/#/
MIT License
420 stars 76 forks source link

`useMountedState` not working in React 18 StrictMode #291

Open molinla opened 1 month ago

molinla commented 1 month ago

Basic Info

Extra info

我尝试并测试过,在 React 16 中可以生效,但在 React 18 中则会失效:

export function useMountedState<S>(initialState: S | (() => S)) {
    const [state, setState] = useState<S>(initialState);
    const leavingRef = useRef(false);
    const setValidState = useCallback<typeof setState>(value => {
        if (leavingRef.current) {
            return;
        }
        setState(value);
    }, []);
    useEffect(
        () => () => {
            leavingRef.current = true;
        },
        [],
    );
    const result: [S, typeof setState] = [state, setValidState];
    return result;
}

将 'useEffect' 中的函数更改为以下代码:

useEffect(
        () => {
            leavingRef.current = false;
            return () => {
                leavingRef.current = true;
            };
        },
        [],
    );

这相当于在组件重新加载后把 leavingRef 重置为 false。

What is expected?

在 React 18 中如果启用了 StrictMode,会导致 arcoDesign 库里面 hook.ts 封装的 useMountedState 失效。

Steps to reproduce

点击样例中的 Picker 选择器,你会发现 onChange 事件传递的数据始终不更新