react hooks useEffect() cleanup for only componentWillUnmount?

前端 未结 5 1401
南笙
南笙 2020-12-12 12:32

Let me explain the result of this code for asking my issue easily.

const ForExample = () => {
    const [name, setName] = useState(\'\');
    const [usern         


        
5条回答
  •  星月不相逢
    2020-12-12 12:54

    Since the cleanup is not dependent on the username, you could put the cleanup in a separate useEffect that is given an empty array as second argument.

    Example

    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 (
        
    {name}
    {username}
    ); }; function App() { const [shouldRender, setShouldRender] = useState(true); useEffect(() => { setTimeout(() => { setShouldRender(false); }, 5000); }, []); return shouldRender ? : null; } ReactDOM.render(, document.getElementById("root"));
    
    
    
    

提交回复
热议问题