【发布时间】:2022-01-18 21:22:07
【问题描述】:
我有这个应用程序,它使用第一个 createAsyncThunk 从 API 获取第一页,然后我希望第二个 createAsyncThunk 获取下一页,当用户到达页面底部时触发以无限滚动方式获取数据。
// Gets the First 10 Posts from the API
export const getPosts = createAsyncThunk(
"post/getPosts",
async (apiAddress) => {
const response = await fetch(apiAddress);
if (!response.ok) throw new Error("Request Failed!");
const data = await response.json();
return data;
}
);
// Loads the Next 10 Posts
export const getMorePosts = createAsyncThunk(
"post/getMorePosts",
async (apiAddress) => {
const response = await fetch(apiAddress);
if (!response.ok) throw new Error("Request Failed!");
const data = await response.json();
return data;
}
);
const redditPostSlice = createSlice({
name: "post",
initialState: {
redditPost: {},
isLoading: false,
hasError: false,
moreIsLoading: false,
moreHasError: false,
},
extraReducers: (builder) => {
builder
.addCase(getPosts.pending, (state) => {
state.isLoading = true;
state.hasError = false;
})
.addCase(getPosts.fulfilled, (state, action) => {
state.redditPost = action.payload.data;
state.isLoading = false;
state.hasError = false;
})
.addCase(getPosts.rejected, (state) => {
state.isLoading = false;
state.hasError = true;
})
.addCase(getMorePosts.pending, (state) => {
state.moreIsLoading = true;
state.moreHasError = false;
})
.addCase(getMorePosts.fulfilled, (state, action) => {
state.redditPost = action.payload.data;
state.moreIsLoading = false;
state.moreHasError = false;
})
.addCase(getMorePosts.rejected, (state) => {
state.moreIsLoading = false;
state.moreHasError = true;
});
},
});
我的问题是应用的状态变成了第二页,第一页的内容不见了。
我知道我的问题在这里 state.redditPost = action.payload.data 但我不知道如何将这个新状态附加到前一个状态。
我已经在这玩了几个小时了,真的不知道该怎么办了。
有没有办法将新状态附加到以前的状态?
【问题讨论】:
标签: javascript reactjs redux react-redux redux-thunk