xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

React Hooks & useEffect error All In One

React Hooks & useEffect error All In One

useEffect cleanup

return void / undefined


// Argument of type '() => () => boolean' is not assignable to parameter of type 'EffectCallback'.

    useEffect(() => {
        let isSubscribed = true;
        if(isSubscribed) {
            getAllData();
        }
        return () => isSubscribed = false;
        // return () => {
        //     isSubscribed = false;
        // };
    }, [page, pageSize]);

    useEffect(() => {
        let isSubscribed = true;
        if(isSubscribed) {
            getAllData();
        }
       // return () => isSubscribed = false;
        return () => {
            isSubscribed = false;
        };
    }, [page, pageSize]);

TypeScript

@types/react/index.d.ts 源码

/Users/xgqfrms/Documents/gitlab-projects/ts-app/node_modules/@types/react/index.d.ts

declare const UNDEFINED_VOID_ONLY: unique symbol;
// Destructors are only allowed to return void.
type Destructor = () => void | { [UNDEFINED_VOID_ONLY]: never };

    // NOTE: callbacks are _only_ allowed to return either void, or a destructor.
    type EffectCallback = () => (void | Destructor);

    function useEffect(effect: EffectCallback, deps?: DependencyList): void;
    // NOTE: this does not accept strings, but this will have to be fixed by removing strings from type Ref<T>
    /**
     * `useImperativeHandle` customizes the instance value that is exposed to parent components when using
     * `ref`. As always, imperative code using refs should be avoided in most cases.
     *
     * `useImperativeHandle` should be used with `React.forwardRef`.
     *
     * @version 16.8.0
     * @see https://reactjs.org/docs/hooks-reference.html#useimperativehandle
     */

DefinitelyTyped

https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react/index.d.ts#L62

https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react/index.d.ts#L907

https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react/index.d.ts#L1090

solution

demos

https://codesandbox.io/s/react-useeffect-cleanup-callback-demo-htl88g?file=/src/MyCustomComponent.js

(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!

refs

https://www.cnblogs.com/xgqfrms/p/16894519.html



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2022-02-27 16:49  xgqfrms  阅读(50)  评论(3编辑  收藏  举报