反应钩useEffect()清理仅componentWillUnmount吗?

koo*_*koo 31 reactjs react-hooks

让我解释一下此代码的结果,以便轻松地询问我的问题。

const ForExample = () => {
    const [name, setName] = useState('');
    const [username, setUsername] = useState('');

    useEffect(() => {
        console.log('effect');
        console.log({
            name,
            username
        });

        return () => {
            console.log('cleaned up');
            console.log({
                name,
                username
            });
        };
    }, [username]);

    const handleName = e => {
        const { value } = e.target;

        setName(value);
    };

    const handleUsername = e => {
        const { value } = e.target;

        setUsername(value);
    };

    return (
        <div>
            <div>
                <input value={name} onChange={handleName} />
                <input value={username} onChange={handleUsername} />
            </div>
            <div>
                <div>
                    <span>{name}</span>
                </div>
                <div>
                    <span>{username}</span>
                </div>
            </div>
        </div>
    );
};
Run Code Online (Sandbox Code Playgroud)

ForExample component坐骑,“效果”将被记录。这与有关componentDidMount()

每当我更改名称输入时,都会记录“效果”和“清理”。反之亦然,自从我添加[username]到的第二个参数以来,每次更改用户名输入都不会记录任何消息useEffect()。这与componentDidUpdate()

最后,在ForExample component卸载时,将记录“清理”。这与有关componentWillUnmount()

我们都知道。

总之,只要重新渲染组件(包括卸载),就会调用“清理”

如果要使该组件仅在卸载时记录“清理”,则只需将第二个参数更改useEffect()[]

但是,如果我更改[username][]ForExample component将不再实现componentDidUpdate()for名称输入。

我要做的是,使组件componentDidUpdate()仅支持名称输入和componentWillUnmount()。(仅在卸载组件时记录“清理”)

Meh*_*iee 43

您可以使用多种用途

例如,如果我的变量是data1,我可以在我的组件中使用所有这些

useEffect( () => console.log("mount"), [] );
useEffect( () => console.log("will update data1"), [ data1 ] );
useEffect( () => console.log("will update any") );
useEffect( () => () => console.log("will update data1 or unmount"), [ data1 ] );
useEffect( () => () => console.log("unmount"), [] );
Run Code Online (Sandbox Code Playgroud)

  • 第一个和最后一个 useEffects 之间有什么区别,第一个 useEffect 将在 **willmount** 或 **didmount** 上调用,最后一个 useEffect 返回带有空数组的回调函数,为什么?您能否详细说明一下每个 useEffect 用例我们何时以及如何使用? (7认同)
  • @siluverukirankumar 回调的返回值(函数)是在销毁(卸载事件)时调用的。这就是为什么最后一个例子是 HOC,立即返回函数。第二个参数是 React 查找更改以重新运行此钩子的位置。当它是空数组时,它只会运行一次。 (4认同)
  • 感谢@Georgy知道了,最后一次useEffect返回的回调未清晰显示 (2认同)
  • 因此,如果您创建一个 useEffect 挂钩,并且它返回一个函数..,那么返回函数之前的代码将作为 componentDidMount 运行...并且返回函数中的代码将被调用以用于 componentWillUnmount?这有点令人困惑,所以请确保我理解正确。useEffect(()=&gt;{ // 挂载时运行的代码 ... return()=&gt; { // 卸载时运行的代码}}) 是这样吗? (2认同)
  • 我建议阅读 https://overreacted.io/a-complete-guide-to-useeffect/ 思考生命周期中的钩子并不是那么甜蜜 (2认同)

Tho*_*lle 26

由于清理操作不依赖于username,因此您可以将清理操作放在一个单独的对象中useEffect,该对象将空数组作为第二个参数。

const { useState, useEffect } = React;

const ForExample = () => {
  const [name, setName] = useState("");
  const [username, setUsername] = useState("");

  useEffect(
    () => {
      console.log("effect");
    },
    [username]
  );

  useEffect(() => {
    return () => {
      console.log("cleaned up");
    };
  }, []);

  const handleName = e => {
    const { value } = e.target;

    setName(value);
  };

  const handleUsername = e => {
    const { value } = e.target;

    setUsername(value);
  };

  return (
    <div>
      <div>
        <input value={name} onChange={handleName} />
        <input value={username} onChange={handleUsername} />
      </div>
      <div>
        <div>
          <span>{name}</span>
        </div>
        <div>
          <span>{username}</span>
        </div>
      </div>
    </div>
  );
};

function App() {
  const [shouldRender, setShouldRender] = useState(true);

  useEffect(() => {
    setTimeout(() => {
      setShouldRender(false);
    }, 5000);
  }, []);

  return shouldRender ? <ForExample /> : null;
}

ReactDOM.render(<App />, document.getElementById("root"));
Run Code Online (Sandbox Code Playgroud)
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="root"></div>
Run Code Online (Sandbox Code Playgroud)


Man*_*mar 14

您可以简单地将其写为:

useEffect(() => {
    return () => {};
}, []);
Run Code Online (Sandbox Code Playgroud)


Bar*_*rry 7

为了添加到已接受的答案中,我遇到了类似的问题,并使用类似的方法和下面的人为示例解决了它。在这种情况下,我需要记录一些参数,componentWillUnmount并且如原始问题中所述,我不希望每次更改参数时都记录。

const componentWillUnmount = useRef(false)

// This is componentWillUnmount
useEffect(() => {
    return () => {
        componentWillUnmount.current = true
    }
}, [])

useEffect(() => {
    return () => {
        // This line only evaluates to true after the componentWillUnmount happens 
        if (componentWillUnmount.current) {
            console.log(params)
        }
    }

}, [params]) // This dependency guarantees that when the componentWillUnmount fires it will log the latest params
Run Code Online (Sandbox Code Playgroud)

  • 如果还有人想知道,useEffects 的顺序确实很重要 (4认同)