如何滚动到无限列表的先前状态?

how to scroll to previous state of infinite list?

我的方法是存储 yOffset 然后在组件重新渲染时使用 window.scrollby() 但它不起作用。

从 sessionStorage 中存储和获取值的方法

我的州

  const [users, setUsers] = useState([]);
  const [pageNumber, setPageNumber] = useState(1);
  const [hasMore, setHasMore] = useState(true);
  useEffect(()=>{
    const handleGetPreviousOffset = () => {
      const scrolledIndex = sessionStorage.getItem("scrolledIndex")
      scrolledIndex &&  window.scrollBy(0,scrolledIndex)
    };
    handleGetPreviousOffset()
  },[])

  useEffect(() => {
    const handleScroll = () => {
      sessionStorage.setItem("scrolledIndex",window.scrollY)
    };
    window.addEventListener("scroll", handleScroll);

    return () =>{
      window.removeEventListener("scroll", handleScroll)
    }
  },[]);

从服务器获取列表的方法

const handleFindingUser = async () => {
    setPageNumber((prevState) => prevState + 1);
    const findingCondition = {
      userId: "1",
      height: 160,
      userGender: "Girl",
      age: 25,
      coordinates: [106.70911015078109, 10.920765741379807],
      distance: 100000,
      hobbies: "61a88a564f32ef06a8dfb159",
      pageNumber,
    };

    const users = await dispatch(findingUser(findingCondition, pageNumber));
    switch (true) {
      case users.payload.data.users.length > 0: {
        setUsers((prevState) => {
          return ([...prevState, ...users.payload.data.users]);
        });
        setHasMore(true);
        break;
      }
      case users.payload.data.users.length === 0 ||
        users.payload.data.users.length < 20: {
        setHasMore(false);
        break;
      }
      default:
        break;
    }
  };
  useEffect(() => {
    handleFindingUser();
  }, []);

最后,我使用无限列表库

<InfiniteScroll
            dataLength={users.length} //This is important field to render the next data
            next={handleFindingUser}
            hasMore={hasMore}
            loader={<h4>Loading...</h4>}
            endMessage={
              <p style={{ textAlign: "center" }}>
                <b>Yay! You have seen it all</b>
              </p>
            }
          >
            {users.map((user) => {
              return (
                <div
             
                  key={user.userId}
                  id={user.nickName}
                  className="d-flex"
                  style={{ margin: 12 }}
                >
                  <p>{user.nickName}</p>
                </div>
              );
            })}
          </InfiniteScroll>

我可以看到调用了 handleGetPreviousOffset 函数,但我不知道为什么 window.scrollBy() 仍然不起作用,我错过了什么? 祝大家有个愉快的一天!

您可以保存偏移量,但更好的方法是在 URL 中使用散列(通过 id)并将其保存在本地存储或(sessionStorage)中,完成后将其删除。 有关详细信息,请参阅 this