回调中 redux 动作的良好模式

Good pattern for redux action in callback

假设我有一个 update comment 动作。当用户在 Promise 获得成功结果后更新评论时,我应该关闭评论编辑器。这是我项目中的示例代码:

export const updateComment = (comment,callBack/* ? */) => {
   return (dispatch, getState){
      api.updateComment({...comment}).then((result) => {
             /* Do something */
             callback() /* ? */
       })
    }
}

react component 中,我使用如下代码的操作:

handleUpdateComment(){
  dispatch(actions.updateComment(this.state.comment,this.closeCommentEitor)
}

它运行良好,但我认为关闭评论编辑器不是一个好的模式。我正在寻找一种正确的模式来关闭编辑器而不通过 callBack 就像我所做的那样。

The only thing that updates your application's state is your reducers.

reducer 应该负责更新您的应用程序的状态,而不是您的操作(您现在传递的是 getState)。

建议你看看redux-promise-middleware

中间件启用乐观更新并分派挂起、已完成和已拒绝的操作,这些操作可以被 reducer 拦截。

当您使用 redux-thunk 时,您可以 dispatch 一个动作从另一个动作开始。 您可以做的是,commentEditor 有一个存储在 redux 中的状态,并根据该状态打开或关闭 commentEditor

export const updateComment = (comment, comment_id) => {
   return (dispatch, getState){
      api.updateComment({...comment}).then((result) => {
             /* Do something */
             dispatch({type: 'CLOSE_COMMENT_EDITOR', id: comment_id})
       })
    }
}

在此之后,在 reducer 中执行此操作会更改 redux 存储的状态,例如

import update from 'immutability-helper'


var initialState = [{commentId: '1', commentEditorOpenStatus: false}, {commentId: '2', commentEditorOpenStatus: false}]
const reducer = (state = initialState, action) => {
     switch(action.type) {
         'CLOSE_COMMENT_EDITOR': 
                  const idx = state.findIndex(obj => obj.commentId == action.id);
                  return update(state, {
                         [idx]: {
                              commentEditorOpenStatus: {
                                  $set: false
                               }
                          }
                   })
            // Other action handlers here
            default: return state
     }

}