【发布时间】:2021-02-17 18:49:54
【问题描述】:
我正在学习 Redux + Redux Toolkit。我需要一条建议。
非常基本的例子。我有一些状态切片:
const postsSlice = createSlice({
name: 'posts',
initialState: [],
reducers: {
// ... some other reducers
updatePost(state, payload) {
const { id, title, content } = payload;
const existingPost = state.find(post => post.id === id);
if (existingPost) {
existingPost.title = title;
existingPost.content = content;
} else {
// I want to dispatch some error action because user tries to edit a post that does not exist!
}
}
}
});
所以我有 updatePost 减速器,我将其导出为动作创建者。它使用给定的 ID 更新帖子。如果找不到带有 id 的帖子,我想显示错误消息。假设我有另一个状态片用于具有相应操作的消息。但是我怎样才能从我的减速器中调度它呢?我应该吗?对我来说,这感觉像是一种反模式。
到目前为止,我正在考虑为我的 updatePost 动作创建者导出一个包装器(thunk?)。像这样的:
export const updatePost = payload => (dispatch, getState) => {
const { id } = payload;
const existingPost = getState().posts.find(post => post.id === id);
if (existingPost) {
dispatch(postsSlice.actions.updatePost(payload));
} else {
dispatch(showError('some invalid post error'));
}
};
这个解决方案对我来说看起来很丑陋。首先,它在整个商店状态(getState())上运行。而且,我不确定这是否是我应该使用 thunk 的目的。看起来它们更像是为异步数据获取主等东西而制作的。
【问题讨论】:
标签: reactjs redux redux-thunk redux-toolkit