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

原文地址:https://www.cnblogs.com/Searchor/p/13877966.html