React Hook优化props传入func造成的重复渲染

2021-03-26  本文已影响0人  黎杰_Lj

前言

待优化示例

链接地址: https://codesandbox.io/s/hook-children-component-preformance1-es6bu

在这里插入图片描述

解决思路

memo优化
const Block = memo((props) => {
  const { handleBlockClick } = props
  // 此处省略组件逻辑
  return <div></div>;
});
使用useCallback
const handleBlockClick = useCallback((blockIndex) => {
  const newState = set(
    state,
    [blockIndex, "checked"],
    !state[blockIndex].checked
  );
  setState(newState);
}, [])
使用useRef
const handleBlockClick = (blockIndex) => {
  const newState = set(
    state,
    [blockIndex, "checked"],
    !state[blockIndex].checked
  );
  setState(newState);
}

// 这里请注意, 不能直接使用useRef(handleClick) 替代下面两行,
// 因为useRef中的参数是初始值, 并不会在每次执行useRef时更新ref.current.
const newRef = useRef()
newRef.current = handleBlockClick

// Block组件传入newRef
<Block
  onClick={newRef}
/>
去掉current
const newRefTarget = (...arr) => {
  newRef.current.apply(null, arr)
}
const newRefTarget = useCallback(() => {
  newRef.current.apply(null, arguments)
}, [])

<Block
  onClick={newRefTarget}
/>
抽离逻辑为新的hooks

const useFunction = (callback) => {
  const newRef = useRef()
  newRef.current = callback

  return useCallback((...arr) => {
    newRef.current.apply(null, arr)
  }, [])
}

// Board组件中则使用useFunction生成的绑定索引的handleBlockClick
const handleBlockClick = useFunction((blockIndex) => {
  const newState = set(
    state,
    [blockIndex, "checked"],
    !state[blockIndex].checked
  );
  setState(newState);
})

<Block
  onClick={handleBlockClick}
/>
优化后示例

链接: https://codesandbox.io/s/hook-children-component-preformance2-w0pj5

小结
上一篇 下一篇

猜你喜欢

热点阅读