反应:如何防止这种重新绘制(使用useMemo或useCallback)?

问题描述 投票:0回答:1

编辑:基于@HMR的回答,我提供了他的建议并提供完整的代码

如果我有这样的组件

const wait = ...
cosnt get_new_wallpaper = ...

const Wallpaper = () => {
  const [background, setBackground] = useState()
  const [nextBackground, setNextBackground] = useState()
  const [visible, setVisible] = useState('first') // not changed in this example

  const setNewWallpaper = useCallback(async stillMounted => {
    const wallpaper = await get_new_wallpaper()
    stillMounted && setBackground(wallpaper)

    await wait(2000)
    const wallpaper2 = await get_new_wallpaper()
    stillMounted && setNextBackground(wallpaper2)
  }, [])

  useEffect(() => {
    let stillMounted = true
    const init_new_wallpaper = async () => await setNewWallpaper (stillMounted)
    init_new_wallpaper()
    return function cancel() {
      stillMounted = false
    }
  }, [])

  return (
   <>
    <PureFirst background={background} onClick={setNewWallpaper} />
    <PureSecond background={nextBackground} onClick={setNewWallpaper} />
   </>
  )
}

const First = styled.div`
  display: ${props => (props.visible === 'first' ? 'unset' : 'none')};
  background-image: url('${props => props.background}');
`
const Second = styled.div`
  display: ${props => (props.visible === 'second' ? 'unset' : 'none')};
  background-image: url('${props => props.background}');
`
const PureFirst = memo(First)
const PureSecond = memo(Second)

[当setNewWallpaper()更改background时,我看到<First>相应地更改,然后等待2秒,然后当它更改nextBackground时,我还看到<Second>相应地更改]]

如您所见,<First>可见(display:unset;)但看不见<Second>display:none;

[这里是<First>更改后<Second>会重新绘制,即使<Second>看不见,所以在这2秒钟后网站上出现了flash为什么这里没有记住此代码?

编辑:基于@HMR的回答,我提供了他的建议并提供完整的代码,如果我有这样的组件,例如const wait = ... cosnt get_new_wallpaper = ... const Wallpaper =()=> ...] >

javascript reactjs react-hooks repaint memoization
1个回答
0
投票
您可以使用React.memo使第一和第二个纯组件,并使用useCallback确保setNewWallpaper不会在渲染之间更改引用。

我不知道setNewWallpaper的依赖关系是什么,因为您没有发布所有代码,所以我认为没有依赖关系:

© www.soinside.com 2019 - 2024. All rights reserved.