Skip to content

滚动状态bug #4

@chenyucheng

Description

@chenyucheng

`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
return <div id={keepalive_${cacheId}} ref={ref} />;
}
}
export default withKeepAlive;`

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions