React hooks useEffect only on update?

前端 未结 8 948
予麋鹿
予麋鹿 2020-12-12 18:53

If we want to restrict useEffect to run only when the component mounts, we can add second parameter of useEffect with [].



        
相关标签:
8条回答
  • 2020-12-12 19:47

    If you want the useEffect to run only on updates except initial mount, you can make use of useRef to keep track of initialMount with useEffect without the second parameter.

    const isInitialMount = useRef(true);
    
    useEffect(() => {
      if (isInitialMount.current) {
         isInitialMount.current = false;
      } else {
          // Your useEffect code here to be run on update
      }
    });
    
    0 讨论(0)
  • 2020-12-12 19:47

    You can get around it by setting the state to a non-boolean initial value (like a null value) :

      const [isCartOpen,setCartOpen] = useState(null);
      const [checkout,setCheckout] = useState({});
    
      useEffect(() => {
    
        // check to see if its the initial state
        if( isCartOpen === null ){
    
          // first load, set cart to real initial state, after load
          setCartOpen( false );
        }else if(isCartOpen === false){
    
          // normal on update callback logic
          setCartOpen( true );
        }
      }, [checkout]);
    
    0 讨论(0)
提交回复
热议问题