UNPKG

xph-form

Version:

This is a configurable form component that supports React

32 lines (31 loc) 1.14 kB
import { useEffect, useRef } from "react"; import { isEqual, isFunction } from "lodash-es"; const useApiComonentCache = (props) => { const { immediate = true, params, api, apiCallback, isUseWatch } = props; const firstRender = useRef(true); const lastTParams = useRef(params); const getApiData = () => { if (api && isFunction(api)) { params ? api(params).then(apiCallback) : api().then(apiCallback); lastTParams.current = params; } }; useEffect(() => { /** 首次请求 */ if (firstRender.current) { immediate ? getApiData() : null; firstRender.current = false; } /** 非首次请求(只有isUseWatch情况才会有非首次请求) */ if (!firstRender.current && isUseWatch) { /** 这次的parmas和上次的params进行对比,只有不一致才需要重新请求 */ if (!isEqual(params, lastTParams.current)) { immediate ? getApiData() : null; } } }, [params]); return { getApiData, }; }; export default useApiComonentCache;