React常用包

2022-07-04  本文已影响0人  我叫Aliya但是被占用了

React-Query

// 初始化
import { useQuery, QueryClient } from 'react-query'
const queryClient = new QueryClient()

function App() {
  return ( 
    <QueryClientProvider client={queryClient}>
        <Todos />
    </QueryClientProvider>
    )
}

查询并缓存 useQuery

const { 
  isLoading, 
  isError, 
  isSuccess, // 查询成功且数据可用
  isIdle,        // 查询当前已禁用/未开始
  isFetching,
  status,    // "idle" | "error" | "loading" | "success"
  data, 
  error,
  refetch,   // 用于刷新请求,参数为最后一次调用的参数
} = useQuery('unique key', promiseFn, { 
  enabled: true,     // false => isIdle true
  staleTime: 0,      // 默认不缓存
  refetchOnWindowFocus: false, // 自动刷新当窗口聚焦
  retry: 3,
  retryDelay: 1000,  // 递增,极限30s
  placeholderData,
  initialData,       // 会缓存
})
// 并发查询
const userQueries = useQueries(
  users.map(user => {
    return {
      queryKey: ['user', user.id],
      queryFn: () => promiseFn(user.id),
    }
  })
)
// (非分页)预加载
queryClient.prefetchQuery('unique key', promiseFn, { staleTime: 5000 })
// 直接写缓存
queryClient.setQueryData('unique key', data)

删除缓存

queryClient.invalidateQueries()
queryClient.invalidateQueries('todos')
queryClient.invalidateQueries('todos', { exact: true })
queryClient.invalidateQueries(['todos', { type: 'done' }])
queryClient.invalidateQueries({
   predicate: query =>
     query.queryKey[0] === 'todos' && query.queryKey[1]?.version >= 10,
 })

更新或删除 useMutation

const { 
  isLoading, 
  isError, 
  isSuccess, // 查询成功且数据可用
  isIdle,        // 查询当前已禁用/未开始
  status,    // "idle" | "error" | "loading" | "success"
  data, 
  error,
  mutate,
  mutateAsync,
} = useMutation(promiseFn, { retry: 3, onMutate })
// 执行
mutate(params, {
  onError,
  onSuccess,
})
// OR
mutateAsync(params).then(...)
queryClient.setMutationDefaults('unique key', {
  mutationFn: addTodo,
  onMutate: () => object,
  retry: 3   
})
  
const mutation = useMutation('addTodo')
mutation.mutate({ title: 'title' })

ahooks 🎉

import { useRequest } from 'ahooks';
// 自动触发
const { data, error, loading } = useRequest(promiseFn);

// 手动触发
const { loading, run, runAsync } = useRequest(promiseFn, {
  manual: true,
  onBefore,  // 生命周期配置项
  onSuccess, // 生命周期配置项
  onError,   // 生命周期配置项
  onFinally, // 生命周期配置项
});
run()
// or
runAsync().then(...)
const { 
  data,
  error,
  loading, 
  run, 
  runAsync,
  refresh,   // 使用上一次的参数,重新发起请求
  refreshAsync, 
  mutate,        // 立即变更数据 mutate(data | (oldData) => newData);
  cancel,    // 取消请求
  params,    // 当次调用的参数数组
} = useRequest(promiseFn, {
  manual: true,
  defaultParams,
  onBefore,  // 生命周期配置项
  onSuccess, // 生命周期配置项
  onError,   // 生命周期配置项
  onFinally, // 生命周期配置项
  loadingDelay: 0,  // 延迟 loading 变成 true 的时间,优化 loading 动画闪烁
  ready: true, 
  refreshDeps: [],  // 依赖刷新,数组中的变量发生变化后,自动重新请求
  // 请求间隔大于 5000ms,窗口聚焦后会刷新请求
  refreshOnWindowFocus: false,   
  focusTimespan: 5000,  
  // 轮询,> 0 启动;用 cancel 停止轮询
  pollingInterval: 0,        // 轮询间隔
  pollingWhenHidden: false,
  // 防抖,> 0 启动;cancel 可以中止正在等待执行的函数
  debounceWait: 0,        // 防抖等待时间 
  debounceLeading: false,   // 延迟开始前执行
  debounceTrailing: true, // 延迟结束后执行
  debounceMaxWait: 0,           // 
  // 节流,> 0 启动;cancel 可以中止正在等待执行的函数
  throttleWait: 0,
  throttleLeading: false,   // 节流开始前执行
  throttleTrailing: true, // 节流结束后执行
  // 缓存
  cacheKey: '有值启用缓存机制',
  cacheTime: 300000,            // 缓存回收时间,-1永不回收,过期后删除
  staleTime: 0,                     // 保鲜时间,-1永远新鲜,过期后重发请求
  setCache: (data: CachedData) => void,  // 自定义缓存,cacheTime、clearCache作废
  getCache: (params: TParams) => CachedData, // 与 setCache 配套使用
});
// 清空 一个|一组|所有 缓存
clearCache(cacheKey?: string | string[]);

State 相关HOOKS

// react
const [obj, setObj] = useState({ a: 10, b: 20 });
setObj({ ...obj, a: 100 }) // 必须整体更新

// import { useSetState } from 'ahooks';
const [obj, setObj] = useSetState({ a: 10, b: 20 });
setState({ a: 100 }) // 可以部分更新

// const [state, { toggle, set, setTrue, setFalse }] = useBoolean(boolean)
// const [state, { toggle, set, setLeft, setRight }] = useToggle(val, otherVal);

// import { useSafeState } from 'ahooks';
const [value, setValue] = useSafeState(''); 
// 用法与 React.useState 完全一样,组件卸载后 SET 方法不再执行,防止内存泄漏???

// import { useGetState } from 'ahooks';
const [count, setCount, getCount] = useGetState<number>(0);
// 比 React.useState 多了 GET 方法,以获取当前最新值?
URL管理 @ahooksjs/use-url-state :基于 react-router 5.x 及以上,且包需要单独安装
import useUrlState from '@ahooksjs/use-url-state';
// 操作 URL 参数,SET 为合并不是替换
const [state, setState] = useUrlState(
  { redirect_to: '/home' }, 
  {
    navigateMode: 'push',  // 'push' | 'replace'
    parseOptions: NULL,    // query-string parse 的配置
    stringifyOptions: NULL,// query-string stringify 的配置
  });
操作COOKIE、LocalStorage、SessionStorage
import { useCookieState } from 'ahooks';
// 自动从COOKIE中取,SET方法自动存(合并非替换)
const [userinfo, setUserinfo] = useCookieState('userinfo', {
  defaultValue: string | undefined | (() => (string | undefined)),
    expires: number | Date,
    path:   '/',
    domain: string,
    secure: false,  // 传输是否需要 https 安全协议
    sameSite
});

// LocalStorage
const [userinfo, setUserinfo] = useLocalStorageState('userinfo', {
  defaultValue: any | (() => any),
  serializer: JSON.stringify,     // 自定义序列化方法 (value: any) => string
  deserializer: JSON.parse
});

// SessionStorage 使用方法与 LocalStorage 一样
防抖、节流 HOOKS

防抖是 变更重新计时,超过延时后发请求;节流是 延时内只发一次请求。

import { useDebounce, useThrottle } from 'ahooks';

const [value, setValue] = useState<string>();
const debouncedValue = useDebounce(value, { wait: 500 }); // 停止输入500ms后变更
const throttledValue = useThrottle(value, { wait: 500 }); // 每隔500ms变更一次
MAP、SET
import { useMap, useSet } from 'ahooks';

const [map, { 
  set: (key: any, value: any) => void, 
  setAll: (newMap) => void, 
  remove: (key: any) => void, 
  reset: () => void,  // 默认值为传进来的初始值?
  get: (key: any) => MapItem
}] = useMap(Map<any>);

const [set, { 
    add: (key: any) => void, 
  remove: (key: any) => void, 
    reset: () => void
}] = useSet(['Hello']);

常用ANT组件、网络状态等功能的HOOKS

纯DOM操作HOOKS

Effect 相关HOOKS

// 自带防抖、节流功能的 Effect
import { useDebounceEffect, useThrottleEffect } from 'ahooks';
useThrottleEffect(
  () => { console.log('value changed') },
  [value],
  { wait: 500 }
);

// 定时器
import { useInterval, useTimeout } from 'ahooks';
const clear = useInterval(
  () => { ... }, 
  1000, 
  { immediate: false }   // 是否首次渲染立即执行
);
clear() // 清除定时器
         
// 强制刷新组件
import { useUpdate } from 'ahooks';
const reReader = useUpdate();
const onClick = () => reReader()
上一篇 下一篇

猜你喜欢

热点阅读