Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

useMountedState not working in React 18 StrictMode #291

Open
1 task done
molinla opened this issue Oct 19, 2024 · 0 comments
Open
1 task done

useMountedState not working in React 18 StrictMode #291

molinla opened this issue Oct 19, 2024 · 0 comments
Assignees

Comments

@molinla
Copy link
Contributor

molinla commented Oct 19, 2024

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 事件传递的数据始终不更新

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants