我目前正在开发一个使用无限滚动来加载更多帖子的社交媒体应用程序。我通过对从我的数据库返回的结果进行分页来做到这一点。每当用户达到某个阈值时,我希望“下一个”道具调用我的 fetch 函数。这将增加路由中的页码并获取下一组帖子。但是,当我尝试这样做时,它无法正常工作。我不确定是否与所使用的操作或减速器本身有关。我该如何解决这个问题?
组件的 JSX:
const posts = useSelector((state) => state.posts);
const totalPages = useSelector(
(state) => state.totalPages
);
useEffect(() => {
setPosts(dispatch);
}, []);
let page = 0;
const fetchMorePosts = () => {
page++;
setPosts(dispatch, page);
};
<PostContainer2>
<InfiniteScroll
dataLength={posts.length}
next={fetchMorePosts}
hasMore={
totalPages === posts.length / 2
? false
: true
}
loader={
<Space
size='middle'
className='spinner'
>
<Spin size='large'></Spin>
</Space>
}
height={300}
scrollThreshold='100px'
>
{posts != null ? (
posts.map((post, idx) => {
return (
<Post
key={idx}
postInfo={post}
></Post>
);
})
) : (
<Space
size='middle'
className='spinner'
>
<Spin size='large'></Spin>
</Space>
)}
</InfiniteScroll>
</PostContainer2>
还原动作:
import {
GET_POSTS,
GET_PAGES,
} from '../../action-types/posts-action-types';
export const setPosts = async (dispatch, pageNum = 0) => {
try {
const response = await fetch(
`http://localhost:4001/user/post?page=${pageNum}&size=2`,
{
method: 'GET',
headers: { token: localStorage.token },
}
);
const parseResponse = await response.json();
dispatch({
type: GET_PAGES,
payload: parseResponse.totalPages,
});
dispatch({
type: GET_POSTS,
payload: parseResponse.content,
});
} catch (err) {
console.error(err.message);
}
};
帖子减速器:
import { GET_POSTS } from '../../action-types/posts-action-types';
const initialState = [];
const posts = (state = initialState, action) => {
switch (action.type) {
case GET_POSTS:
state = [...state, ...action.payload];
state.sort((a, b) => b.id - a.id);
return state;
default:
return state;
}
};
export default posts;
总页数缩减器:
import { GET_PAGES } from '../../action-types/posts-action-types';
const initialState = 0;
const totalPages = (state = initialState, action) => {
switch (action.type) {
case GET_PAGES:
state = action.payload;
return state;
default:
return state;
}
};
export default totalPages;