我创建了一个网站并使用了redux-toolkit,但我对createSlice有一个问题。我的两条记录数据接收正确。但是当我将数据设置到适配器中时,只添加了第一条记录。这是我的切片代码
import { createEntityAdapter, createSlice, PayloadAction, createSelector, createAsyncThunk } from "@reduxjs/toolkit";
import { fetchTop10Podcasts } from "../../../services/endpoints/Podcasts";
import { podcastState } from "../../initialStates/Podcasts";
const podcastAdapter = createEntityAdapter();
// interface podcastState {
// entities: Array<Podcast>
// loading: 'idle' | 'loading' | 'successed' | 'failed'
// }
export const PodcastSlice = createSlice({
name: 'podcasts',
initialState: podcastAdapter.getInitialState({
entities: [],
loading: 'idle'
} as podcastState),
reducers: {
}, extraReducers: (builder) => {
builder.addCase(fetchTop10Podcasts.pending, (state, action) => {
state.loading = 'loading';
}).addCase(fetchTop10Podcasts.fulfilled, (state, action) => {
state.loading = 'successed';
podcastAdapter.setAll(state, action.payload.data.podcasts)
console.log('podcasts', action.payload.data.podcasts); // here I recieved two record
}).addCase(fetchTop10Podcasts.rejected, (state, action) => {
state.loading = 'failed';
})
}
});
export const {
selectById: selectPodcastById,
selectAll: selectPodcasts
} = podcastAdapter.getSelectors((state: any) => state.podcasts)
export const selectPodcastIds = createSelector(
selectPodcasts,
podcasts => podcasts.map((podcast: any) => podcast._id)
)
export default PodcastSlice.reducer;发布于 2021-11-04 16:19:39
我认为问题可能与您的初始状态有关。
当您调用adapter.getInitialState()时,它返回的状态结构是{ids: [], entities: {}},外加您传入的任何附加字段。
您将提供entities: []作为附加字段。结果很可能是覆盖了原始的对象结构。
去掉这一行,我想这就行了。
https://stackoverflow.com/questions/69828362
复制相似问题