zoukankan      html  css  js  c++  java
  • React Hooks 之 useEffect

    函数定义

        /**
         * Accepts a function that contains imperative, possibly effectful code.
         * 接受包含命令性的,可能有效的代码的函数。
         *
         * @param effect Imperative function that can return a cleanup function. 可以返回清除函数的命令式函数。
         * @param deps If present, effect will only activate if the values in the list change. 如果存在,则仅当列表中的值更改时,Effect才会激活。
         *
         * @version 16.8.0
         * @see https://reactjs.org/docs/hooks-reference.html#useeffect
         */
        function useEffect(effect: EffectCallback, deps?: DependencyList): void;
    

    相关类型别名:

        type EffectCallback = () => (void | (() => void | undefined)); // 回调只允许返回void或析构函数。析构函数本身仅允许返回void。
    
        type DependencyList = ReadonlyArray<any>;
    

    什么是Effect(副作用)

    副作用,是对状态的一种监听方式。当状态(或常规变量)被初始化后或改变后,Effect会被执行,在此之前会先执行上一次Effect返回的清除函数(初始化除外)。

    useEffect用法

    import './index.html';
    import * as React from 'react';
    import * as ReactDOM from 'react-dom';
    
    var FC: React.FC<{ arr: string[] }> = (props, ctx) => {
        var [array, setArray] = React.useState(props.arr);
        React.useEffect(() => {
            console.log('状态初始化或更新为', array);
            return () => {
                console.log('状态发生了变化', array);
            };
        }, [array]);
        return (
            <div>
                {array.map(it => <h1 style={{ color: 'red' }}>{it}</h1>)}
                <button onClick={() => {
                    array.pop();
                    setArray([...array]);
                }}>pop</button>
            </div>
        );
    };
    
    ReactDOM.render(<div>
        <FC arr={['Java', 'C++', 'Node.js']}></FC>
    </div>, /* container */ document.querySelector('#app'));
    

    useEffect模拟componentDidMount

    deps?: React.DependencyList设置为一个常量数组即可,例如空数组[]或者[true][1, 2, 3]都可以。

        React.useEffect(() => {
            console.log('该Effect函数每个组件实例只在组件挂载后执行一次');
            div.current?.offsetTop && setHeight(`calc(100vh - ${div.current.offsetTop}px)`);
        }, []);
    

  • 相关阅读:
    A. Dreamoon and Stairs(Codeforces Round #272)
    bootstrap之UpdateStrings
    FZU
    IT忍者神龟之 oracle行转列、列转行
    linux find 10天内改动过的文件
    内核调试日志打印宏
    ack-grep 代码全文搜索
    JDK配置 linux
    IDA修改游戏
    curl 访问https问题
  • 原文地址:https://www.cnblogs.com/develon/p/14268150.html
Copyright © 2011-2022 走看看