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

  • 相关阅读:
    ElasticSearch基本学习
    Liunx下的系统负荷
    记录调试树(方便跟到具体的调用)
    树形结构的数据库的存储
    VS快速生成JSON数据格式对应的实体
    关于理想化的编程
    通过Chrome浏览器检测和优化页面
    一个关于Random算法的问题
    MVC中的一般权限管理
    文件读写锁
  • 原文地址:https://www.cnblogs.com/Searchor/p/13877966.html
Copyright © 2011-2022 走看看