我在React中使用useRef钩子,这样如果刷新页面,并且该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;