1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| 实现思路: 1、状态设计(以帖子列表为例): { posts: { list: [], page: 1, pageSize: 10, loading: false, hasMore: true, error: null } }
2、异步 action(使用 thunk 或 asyncThunk): export const fetchPosts = createAsyncThunk( 'posts/fetch', async ({ page }, thunkAPI) => { const res = await fetch(`https://api.com/posts?page=${page}`); return await res.json(); } );
3、Reducer 处理追加列表: extraReducers: (builder) => { builder.addCase(fetchPosts.fulfilled, (state, action) => { state.list = [...state.list, ...action.payload]; state.page += 1; state.hasMore = action.payload.length > 0; }); }
4、前端触发加载更多(如 FlatList onEndReached): onEndReached={() => { if (hasMore && !loading) { dispatch(fetchPosts({ page })); } }}
|