【发布时间】:2021-03-03 00:51:18
【问题描述】:
我是 Redux 的新手,从一开始就尝试使用 RTK,到目前为止,这对我来说是一个令人困惑的挑战。
现在我试图在我的切片中添加一个普通的 Reducer 而不是一个 extraReducer,我得到了我无法理解的奇怪结果。当我完全删除减速器声明时,一切都按预期工作。帖子被加载到道具中。
var initialState = { entities: [], ids: [], fetchState: "idle", current: 0 };
export const postSlice = createSlice({
name: "posts",
initialState: initialState,
reducers: {
currentPostChanged: (state, action) => {},
},
extraReducers: {
[fetchAll.pending]: (state, action) => {
state.fetchState = "pending";
},
[fetchAll.rejected]: (state, action) => {
state.fetchState = "rejected";
},
[fetchAll.fulfilled]: (state, action) => {
var keys = objectFlip(Object.keys(action.payload.entities.posts));
var posts = Object.values(action.payload.entities.posts);
state.entities = posts;
state.ids = keys;
state.fetchState = "idle";
},
},
});
export const postReducer = postSlice.reducer;
存储配置
var storeConfig = {
reducer: {
posts: postReducer,
},
middleware: [...getDefaultMiddleware()],
devTools: process.env.NODE_ENV !== "production",
};
const store = configureStore(storeConfig);
映射状态
function mapStateToProps(state) {
console.log(state);
return {
posts: state.posts.entities,
postsIds: state.posts.ids,
};
}
获取完成前的输出
posts: {…}
entities: Object {}
ids: Array []
提取完成后的输出
posts: {…}
entities: Array(28) [ {…}, {…}, {…}, … ]
fetchState: "idle"
ids: Object { 2: "0", 3: "1", 4: "2", … }
React 组件中的渲染方法
render() {
if (this.props !== undefined) {
console.log("Component.render()");
console.log(this.props);
}
return <div></div>
}
输出
【问题讨论】:
标签: javascript reactjs redux redux-thunk redux-toolkit