UNPKG

@ovine/core

Version:

Build flexible admin system with json.

49 lines (48 loc) 1.72 kB
/** * https://github.com/podefr/react-debounce-render/blob/master/src/index.js * 防止组件短时间内连续并发渲染 */ import hoistNonReactStatics from 'hoist-non-react-statics'; import { debounce as lodashDebounce, uniqueId } from 'lodash'; import React, { Component, useEffect, useMemo, useRef, useState } from 'react'; function debounceRender(ComponentToDebounce, wait, setting) { const DebounceComponent = ComponentToDebounce; // @ts-ignore class DebouncedContainer extends Component { constructor() { super(...arguments); this.updateDebounced = lodashDebounce(this.forceUpdate, wait, setting); } shouldComponentUpdate() { this.updateDebounced(); return false; } componentWillUnmount() { this.updateDebounced.cancel(); } render() { return React.createElement(DebounceComponent, Object.assign({}, this.props)); } } return hoistNonReactStatics(DebouncedContainer, DebounceComponent); } export const useDebounceRender = (option, deeps) => { const { getComponent, wait, setting } = option; const [refreshKey, setRefreshKey] = useState(''); const refreshTrigger = useRef(); useEffect(() => { if (!refreshTrigger.current) { refreshTrigger.current = lodashDebounce(() => { setRefreshKey(uniqueId()); }, wait, setting); } if (wait) { refreshTrigger.current(); } }, deeps); const CachedComponent = useMemo(() => { return !refreshKey ? null : getComponent(); }, [refreshKey]); return CachedComponent; }; export default debounceRender;