react常用hooks
useMount
const useMount = (callback) => {
React.useEffect(callback, [])
}
useUnmounted
1 const useUnmount = (callback) => { 2 const callbackRef = React.useRef(callback) 3 4 callbackRef.current = callback 5 6 React.useEffect(() => { 7 return () => { 8 callbackRef.current() 9 } 10 }, []) 11 }
定时器
1 import React, {useState, useEffect} from "react" 2 3 const Counter = ({initialCount = 0}) => { 4 const [count, setCount] = useState(initialCount) 5 6 useEffect(() => { 7 const timerId = setInterval(() => { 8 setCount(prevCount => prevCount + 1) 9 }, 1000) 10 11 return () => clearInterval(timerId); 12 }, []) 13 14 return ( 15 <div> 16 <h1>当前计数:{count}</h1> 17 </div> 18 ) 19 } 20 21 export default Counter
部分更新state
1 import React, {useState, useEffect} from "react" 2 3 const useSetState = (initState) => { 4 const [state, setState] = React.useState(initState) 5 6 const setMergeState = (value) => { 7 setState((prevValue) => { 8 const newValue = typeof value === 'function' ? value(prevValue) : value 9 return newValue ? {...prevValue, ...newValue} : prevValue 10 }) 11 } 12 13 return [state, setMergeState] 14 } 15 16 const Counter = ({initialCount = 0}) => { 17 const [person, setPerson] = useSetState({ 18 name: 'aaaa', 19 age: 100 20 }) 21 const onSetName = () => { 22 setPerson({name: 'bbb'}) 23 } 24 25 return ( 26 <div> 27 <button onClick={onSetName}>改变</button> 28 <div>{person.name}</div> 29 </div> 30 ) 31 } 32 33 export default Counter