Skip to content

Commit

Permalink
✨ fix: 兼容 NextJs 的 window 不存在问题 (#38)
Browse files Browse the repository at this point in the history
  • Loading branch information
ONLY-yours committed Jan 17, 2024
1 parent 4444f40 commit 7bb47a5
Showing 1 changed file with 20 additions and 4 deletions.
24 changes: 20 additions & 4 deletions src/ProChat/components/ScrollAnchor/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { memo, useEffect } from 'react';
import { memo, useEffect, useState } from 'react';
import { useInView } from 'react-intersection-observer';

import { useStore } from '@/ProChat/store';
Expand All @@ -10,15 +10,31 @@ const ChatScrollAnchor = memo(() => {
const trackVisibility = useStore((s) => !!s.chatLoadingId);
const str = useStore(chatSelectors.currentChats);

const [isWindowAvailable, setIsWindowAvailable] = useState(false);

useEffect(() => {
// 检查window对象是否已经可用
if (typeof window !== 'undefined') {
setIsWindowAvailable(true);
}
}, []);

const { ref, entry, inView } = useInView({
delay: 100,
rootMargin: '0px 0px -150px 0px',
trackVisibility,
});

// 如果是移动端,可能200太多了,认为超过 1/3 即可,PC默认200
const ScrollOffset = window.innerHeight / 3 > 200 ? 200 : window.innerHeight / 4;
const isAtBottom = useAtBottom(ScrollOffset);
const [scrollOffset, setScrollOffset] = useState(0);

useEffect(() => {
if (isWindowAvailable) {
// 如果是移动端,可能200太多了,认为超过 1/3 即可,PC默认200
setScrollOffset(window.innerHeight / 3 > 200 ? 200 : window.innerHeight / 4);
}
}, [isWindowAvailable]);

const isAtBottom = useAtBottom(scrollOffset);

useEffect(() => {
if (isAtBottom && trackVisibility && !inView) {
Expand Down

0 comments on commit 7bb47a5

Please sign in to comment.