编辑:基于@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 =()=> ...] >
我不知道setNewWallpaper的依赖关系是什么,因为您没有发布所有代码,所以我认为没有依赖关系: