zoukankan      html  css  js  c++  java
  • xml ui

    A custom Hook is a JavaScript function whose name starts with ”use” and that may call other Hooks

    import { useEffect, useCallback } from "react";
    
    // Custom React Hook
    export default function useEventListener(name, handler, element) {  
    
      const handleEventHandler = useCallback(
        event => {      
          if (typeof handler === "function") {        
            handler(event);      
          }    
        },    
        [handler]  
      );
    
      useEffect(
        () => {      
          // Check if the element supports the addEventListener method
          const checked = element && element.addEventListener;      
          // Stop here if not supported      
          if (!checked) return;      
          // Add event listener      
          element.addEventListener(eventName, handleEventHandler);      
          // Remove event listener on cleanup      
          return () => {       
            element.removeEventListener(name, handleEventHandler);
          };    
        },    
        [name, element, handleEventHandler] 
      );
    }
    
    import { useState, useEffect } from 'react';
    
    function useFriendStatus(friendID) {  const [isOnline, setIsOnline] = useState(null);
    
      useEffect(() => {
        function handleStatusChange(status) {
          setIsOnline(status.isOnline);
        }
    
        ChatAPI.subscribeToFriendStatus(friendID, handleStatusChange);
        return () => {
          ChatAPI.unsubscribeFromFriendStatus(friendID, handleStatusChange);
        };
      });
    
      return isOnline;
    }
    
    const usePerson = (personId) => {
      const [loading, setLoading] = useState(true);
      const [person, setPerson] = useState({});
      useEffect(() => {
        setLoading(true);
        fetch(`https://swapi.co/api/people/${personId}/`)
          .then(response => response.json())
          .then(data => {
            setPerson(data);
            setLoading(false);
          });
      }, [personId]);
      return [loading, person];
    };
    
    
    const Person = ({ personId }) => {
      const [loading, person] = usePerson(personId);
    
      if (loading === true) {
        return <p>Loading ...</p>;
      }
    
      return (
        <div>
          <p>You're viewing: {person.name}</p>
          <p>Height: {person.height}</p>
          <p>Mass: {person.mass}</p>
        </div>
      );
    };
    

    https://react-hooks-cheatsheet.com/
    https://www.ruanyifeng.com/blog/2019/09/react-hooks.html

  • 相关阅读:
    ASP.NET Cache的一些总结分享
    C#中委托和事件的区别实例解析
    [hdu2544]最短路spfa
    [codeforces274b]Zero Tree(树形dp)
    [poj2151]Check the difficulty of problems概率dp
    [poj3071]football概率dp
    [poj3744]Scout YYF I(概率dp+矩阵快速幂)
    [bzoj2440]完全平方数(二分+mobius反演)
    [xdoj1216]子树第k小(dfs序+主席树)
    [xdoj1233]Glory and LCS
  • 原文地址:https://www.cnblogs.com/Searchor/p/13877966.html
Copyright © 2011-2022 走看看