1. useLocalStorge
该 Hook 用于在本地存储中存储和检索数据。在组件之间共享和保持状态,并且在页面重新加载时保持数据的持久性
import { useState } from 'react';
const useLocalStorage = (key, initialValue) => {
const [storedValue, setStoredValue] = useState(() => {
try {
const item = localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
console.error(error);
return initialValue;
}
});
const setValue = (value) => {
try {
const valueToStore = value instanceof Function ? value(storedValue) : value;
setStoredValue(valueToStore);
localStorage.setItem(key, JSON.stringify(valueToStore));
} catch (error) {
console.error(error);
}
};
return [storedValue, setValue];
};
export default useLocalStorage;
使用方法
import useLocalStorage from './hooks/useLocalStorgen'
const [name, setName] = useLocalStorage('name');
useEffect(() => {
setName('Guest')
}, [])
// 支持传递函数
useEffect(() => {
setName(() => {
return '123'
})
}, [])
效果 ==> 字符串
效果 ==> 函数
2. UseFetch
该 Hook 用于进行网络请求并获取数据。在组件中发起异步请求,并管理数据的加载状态,使得处理网络请求变得更加简单和方便,这里做了缓存处理,将get请求的数据存储到本地.
import { useEffect, useState } from 'react'
import useLocalStorage from './useLocalStorgen'
const useFetch = (url, cacahe) => {
const [data, setData] = useState(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState(null);
const [_, setWatherData] = useLocalStorage(url)
useEffect(() => {
const fetchData = async () => {
try {
const cacaheData = localStorage.getItem(url)
if (cacaheData) {
setData(JSON.parse(JSON.parse(cacaheData)))
setLoading(false)
} else {
const response = await fetch(url)
const data = await response.json()
cacahe && setWatherData(JSON.stringify(data))
setData(data)
}
} catch (err) {
setError(err)// 处理错误
} finally {
setLoading(false)
}
}
fetchData()
}, [url])
return [data, loading, error]
}
export default useFetch
加 catch
const [data] = useFetch('https://api.oioweb.cn/api/weather/GetWeather', { catch: true })
console.log(data)
效果
再次刷新也不会发送请求了
去掉 catch后
const [data] = useFetch('https://api.oioweb.cn/api/weather/GetWeather')
console.log(data)
效果
刷新后会发送请求
3. useDebounce
该 Hook 用于延迟某个值的更新,通常用于处理用户输入的延迟搜索或其他需要防抖的场景。它可以帮助减少不必要的请求或计算,提高性能并提升用户体验
import { useEffect, useState } from 'react';
const useDebounce = (value, delay) => {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const handle = setTimeout(() => {
setDebouncedValue(value)
}, delay)
return () => {
clearTimeout(handle)
}
}, [value, delay])
return debouncedValue; // 返回一个延迟更新的值
}
export default useDebounce
使用
import useDebounce from './hooks/useDebounce'
function SeacrComponent(){
const [inputValue, setInputValue] = useState('');
const debouncedSearchTerm = useDebounce(inputValue, 500);
const handleChange = (event) => {
setInputValue(event.target.value);
};
useEffect(() => {
if (debouncedSearchTerm) {
console.log('Searching for:', debouncedSearchTerm);
}
}, [debouncedSearchTerm]);
return (
<>
<input
type="text"
value={inputValue}
onChange={handleChange}
placeholder="Search..."
/>
</>
)
}
效果
4. usePrevious
该 Hook 用于获取之前的状态值.
import { useEffect, useRef } from 'react';
const usePrevious = (value) => {
const ref = useRef();
// 保存上一次的值
useEffect(() => {
ref.current = value;
}, [value]);
// 返回上一次的值
return ref.current;
}
export default usePrevious
使用
import usePrevious from './hooks/usePrevious'
const prevValue = usePrevious(count)
const [inputValue, setInputValue] = useState('');
useEffect(() => {
if (prevValue !== undefined && count !== prevValue) {
console.log(`值从${prevValue}改为${count}了`)
}
}, [count, prevValue])
<h1>当前值:{count}</h1>
<h1>上一次的值:{prevValue}</h1>
<button onClick={() => { setCount(count + 1) }}>点我+1</button>
效果
5. useToogle
该Hook用于在布尔值之间切换
import { useState } from 'react'
const useToggle = (initalValue = false) => {
const [value, setValue] = useState(initalValue)
const toggle = () => {
setValue(prev => !prev)
}
return [value, toggle]
}
export default useToggle
使用
const [isToogle, toogle] = useToggle(true)
{isToogle && <div style={{ width: '200px', height: '200px', background: 'red' }}> </div>}
<button onClick={toogle}>
{isToogle ? '显示' : '隐藏'}
</button>
效果 ==> 为 true 时
效果 ==> 为 false 时