keepalive-react-component icon indicating copy to clipboard operation
keepalive-react-component copied to clipboard

滚动状态bug

Open chenyucheng opened this issue 3 years ago • 0 comments

`import { useState } from 'react';

function List(props) {

let [arr, setArr] = useState(Array(50).fill(0))
let [isShow, setIsShow] = useState(true)
return <div>
    <button onClick={() => {
        props.dispatch({ type: 'DESTROY', payload: { cacheId: 'list' } })
        setIsShow(!isShow)
        setArr(Array(100).fill(0))
    }}>增加</button>
    {isShow ? <div>111111</div> : null}
    <ul style={{ height: '100px', overflow: 'auto' }}>
        {arr.map((item, index) => {
            return <li key={index}>{index}</li>
        })}
    </ul>
    <ul style={{ height: '100px', overflow: 'auto',marginTop:'20px' }}>
        {arr.map((item, index) => {
            return <li key={index}>{index}</li>
        })}
    </ul>
</div>

}

export default List`

滚动状态记录有问题:

scrolls:new Map() 使用map 记录

回写状态 递归处理元素

`import React, { useContext, useRef,useEffect } from "react"; import CacheContext from './CacheContext'; import * as cacheTypes from './cache-types';

const setScrollTop=(dom,cacheState)=>{ const next=(dom)=>{ if(cacheState.scrolls.get(dom)){ dom.scrollTop = cacheState.scrolls.get(dom); } Array.from(dom.children).forEach(item=>{ next(item) }) } next(dom) } function withKeepAlive(OldComponent, { cacheId = window.location.pathname,scroll=false }) { return function (props) { const {mount, cacheStates,dispatch,handleScroll } = useContext(CacheContext); const ref = useRef(null); useEffect(()=>{ if(scroll){ ref.current.addEventListener('scroll', handleScroll.bind(null, cacheId),true); } },[handleScroll]); useEffect(() => { let cacheState = cacheStates[cacheId]; if(cacheState&&cacheState.doms && cacheState.status !== cacheTypes.DESTROY){ let doms = cacheState.doms; doms.forEach(dom=>ref.current.appendChild(dom)); if(scroll){ // 递归解决 doms.forEach(dom=>{ setScrollTop(dom,cacheState)
}); } }else{ mount({ cacheId, element:<OldComponent {...props} dispatch={dispatch}/>}) } }, [cacheStates, dispatch, mount, props]); // return <OldComponent></OldComponent> return <div id={keepalive_${cacheId}} ref={ref} />; } } export default withKeepAlive;`

chenyucheng avatar Jan 25 '23 16:01 chenyucheng