customHook 自定义事件 (二)

105 阅读1分钟

获取数据是我每次创建React应用时都会做的事情,进行了好多个这样的重复获取

useFetch 自定义

const useFetch = (url = '', options = null) => { 
    const [data, setData] = useState(null); 
    const [error, setError] = useState(null); 
    const [loading, setLoading] = useState(false); 
    
    useEffect(() => { 
        let isMounted = true; 
        setLoading(true); 
        fetch(url, options)
            .then(res => res.json()) 
            .then(data => { 
                if (isMounted) { 
                    setData(data); setError(null); 
             }})
             .catch(error => { 
                if (isMounted) { 
                    setError(error); 
                    setData(null); 
             }}) 
             .finally(() => isMounted && setLoading(false)); 
             
        return () => (isMounted = false);
    }, [url, options]); 
    
    return { loading, error, data }; 
}; 

调用时:-----------------------------------------
const {loading, error, data=[]} = useFetch('/api/v1/search?param=test);

大家都比较常用的,拿浏览器缓存,LocalStorage

useLocalStorage 将包含有状态值和在将其持久存储在localStorage 中时对其进行更新的函数

const useLocalStorage = (key = '', initialValue = '') => { 
    const [state, setState] = useState(() => { 
        try { 
            const item = window.localStorage.getItem(key); 
            return item ? JSON.parse(item) : initialValue; 
         } catch (error) { 
             return initialValue; 
         } }); 
     const setLocalStorageState = newState => { 
         try { 
             const newStateValue = typeof newState === 'function' ? newState(state) : newState; 
             setState(newStateValue); 
             window.localStorage.setItem(key, JSON.stringify(newStateValue)); 
         } catch (error) { 
             console.error(`Unable to store new value for ${key} in localStorage.`); 
         } 
     };
     return [state, setLocalStorageState]; 
 };

调用时:------------------------------------
const [appSettings, setAppSettings] = useLocalStorage(xxx , xxxx)
setAppSettings({ notifications: 'weekly'})
onChange={e => setAppSettings(settings => ({ 
    ...settings, 
    notifications: e.target.value
})) }

这个自定义Hook,感觉没什么用,但还是先撸为敬

useMediaQuery监控媒体查询

const useMediaQuery = (queries = [], values = [], defaultValue) => { 
    const mediaQueryList = queries.map(q => window.matchMedia(q)); 
    const getValue = useCallback(() => { 
        const index = mediaQueryList.findIndex(mql => mql.matches); 
        return typeof values[index] !== 'undefined' ? values[index] : defaultValue; 
    }, [mediaQueryList, values, defaultValue]);
    
    const [value, setValue] = useState(getValue); 
    
    useEffect(() => { 
        const handler = () => setValue(getValue); 
        mediaQueryList.forEach(mql => mql.addEventListener('change', handler)); 
        
        return () => 
            mediaQueryList.forEach(mql => mql.removeEventListener('change', handler)); 
    }, [getValue, mediaQueryList]); 
        
    return value;
};

调用时:------------------------------------
const canHover = useMediaQuery( 
    ['(hover: hover)'], 
    [true], 
    false
);
<div className={canHover ? hoverClass : defaultClass}>fuckup!!!</div>

结语

前端react QQ群:788023830 ---- React/Redux - 地下老英雄

前端交流 QQ群:249620372 ---- FRONT-END-JS前端

(我们的宗旨是,为了加班,为了秃顶……,仰望大佬),希望小伙伴们加群一起学习