【问题标题】:How to dispatch error action within the reducer?如何在 reducer 中调度错误操作?
【发布时间】: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


    【解决方案1】:

    但是我怎样才能从我的 reducer 中调度它呢?我应该吗?对我来说,这感觉像是一种反模式。

    你就在这里。你永远不应该从 reducer 派发一个动作。

    您的 thunk 示例还不错。但是既然你是在征求意见,我个人的意见是处理编辑帖子的组件应该负责确保帖子存在(你可以使用选择器来做到这一点)。如果帖子 ID 无效,我们应该防止编辑发生。无需将无效的发布错误作为操作发送,这将在组件内部处理。

    const PostEditor = ({id}) => {
    
        const current = useSelector(getPost(id));
    
        const dispatch = useDispatch();
    
        return (
            <div>
                {!! current ? 
                    <EditPost ..../>
                    :
                    <div>Error: Invalid Post ID #{id}</div>
                }
            </div>
        )
    }
    

    【讨论】:

      猜你喜欢
      • 2018-05-07
      • 2018-05-29
      • 2019-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-06
      相关资源
      最近更新 更多