Как запомнить положение прокрутки элемента DOM? - PullRequest
0 голосов
/ 29 мая 2019

Я использую ловушку useRef в React, чтобы при обновлении страницы и прокрутке этого div он запомнил, как далеко прокручен div. Проблема заключается в том, что этот div монтируется в позиции без прокрутки, а затем useEffect прокручивает его, вызывая небольшую, но видимую задержку прокрутки. DIV внезапно перепрыгивает в положение прокрутки. Как я могу решить это?

const PollsBox = (props) => {
const Auth = new AuthService();
const [polls, setPolls] = useState(null);
const ref = useRef(null);

useEffect(() => {
    if (sessionStorage.scrollPosition) {
        console.log('scrolled')
        ref.current.scrollLeft = sessionStorage.scrollPosition;
    }
    Auth.fetch('api/polls/').then((data) => {
        setPolls(data);
    });
    return () => {
        var scrollPosition = ref.current.scrollLeft;
        sessionStorage.setItem("scrollPosition", scrollPosition);
    }
},[props])
const pollsList = () => {
    if (polls == null) return <div></div>
    return polls.map((el) => {
        return (
            <div key={el.id} id="poll-individual">
                <Poll poll={el} />
            </div>
        );
    })
}
return (
    <div className="polls-box" ref={ref}id="polls-box">
        <h5>{props.title}</h5>
        {pollsList()}

    </div>
    );
};


export default PollsBox;
...