ahooks

45 阅读1分钟
  • useEffect & useAsyncEffect
        async await 不能直接这么用
	useEffect(async() => {
		setPass(await mockCheck())
	}, [])
        修改:
        useEffect(() => {
            const temp = async () => {
              setPass(await mockCheck())
            }
        temp()
	}, [])
        
        useAsyncEffect可以直接使用async await :
	useAsyncEffect(
            async () => {
                    setPass(await mockCheck())
            },
            []
	)
        
  • useEffect & useDebounceEffect
useDebounceEffect为useEffect增加防抖的能力
import { useDebounceEffect } from 'ahooks';
import React, {useState} from 'react'
const Petra = () => {
	const [value, setValue] = useState('hello');
  const [records, setRecords] = useState<string[]>([]);
	useDebounceEffect(() => {
		setRecords([value, ...records])
	}, [value], {wait: 1000})
   return (
     <div>
       <input
         value={value}
         onChange={e => setValue(e.target.value)}
         placeholder="Typed value"
         style={{ width: 280 }}
       />
       <p style={{ marginTop: 16 }}>
         <ul>
           {records.map((record, index) => (
             <li key={index}>{record}</li>
           ))}
         </ul>
       </p>
     </div>
   );
};
export default Petra



  • useDebounce
用来处理防抖值的 Hookimport { useDebounce } from 'ahooks';
import React, {useState} from 'react'
const Petra = () => {
	const [value, setValue] = useState('hello');
	const debounceValue = useDebounce(value, {wait: 500})
	return (
     <div>
       <input
         value={value}
         onChange={e => setValue(e.target.value)}
         placeholder="Typed value"
         style={{ width: 280 }}
       />
       <p style={{ marginTop: 16 }}>debounceValue:{debounceValue}</p>
       <p style={{ marginTop: 16 }}>value:{value}</p>
     </div>
   );
};
export default Petra