From fa7e03b9265ea18278ed785a2f48231722dd28d8 Mon Sep 17 00:00:00 2001 From: Haishan Date: Sun, 13 Jan 2019 23:15:54 +0800 Subject: [PATCH] hooks: extract element remaining view port height logic into a hook --- src/components/Rules.js | 19 +++-------------- src/hooks/useRemainingViewPortHeight.js | 27 +++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 16 deletions(-) create mode 100644 src/hooks/useRemainingViewPortHeight.js diff --git a/src/components/Rules.js b/src/components/Rules.js index b282919..8e3f991 100644 --- a/src/components/Rules.js +++ b/src/components/Rules.js @@ -13,6 +13,7 @@ import { FixedSizeList as List, areEqual } from 'react-window'; import ContentHeader from 'c/ContentHeader'; import Rule from 'c/Rule'; import RuleSearch from 'c/RuleSearch'; +import useRemainingViewPortHeight from '../hooks/useRemainingViewPortHeight'; import { getRules, fetchRules, fetchRulesOnce } from 'd/rules'; @@ -45,24 +46,10 @@ const Row = memo(({ index, style, data }) => { export default function Rules() { const { fetchRulesOnce, fetchRules } = useActions(actions); const { rules } = useStoreState(mapStateToProps); - const refRulesContainer = useRef(null); - const [containerHeight, setContainerHeight] = useState(200); - function _updateContainerHeight() { - const { top } = refRulesContainer.current.getBoundingClientRect(); - setContainerHeight(window.innerHeight - top - paddingBottom); - } - const updateContainerHeight = useCallback(_updateContainerHeight, []); - useEffect(() => { fetchRulesOnce(); }, []); - useLayoutEffect(() => { - updateContainerHeight(); - window.addEventListener('resize', updateContainerHeight); - return () => { - window.removeEventListener('resize', updateContainerHeight); - }; - }, []); + const [refRulesContainer, containerHeight] = useRemainingViewPortHeight(); return (
@@ -70,7 +57,7 @@ export default function Rules() {
{ + updateContainerHeight(); + window.addEventListener('resize', updateContainerHeight); + return () => { + window.removeEventListener('resize', updateContainerHeight); + }; + }, []); + + return [refRulesContainer, containerHeight]; +}