【问题标题】:redux-thunk or middleware?redux-thunk 还是中间件?
【发布时间】:2019-01-09 17:38:41
【问题描述】:

我有多个action,之后我必须致电其他 2 个action

我的第一种方法是编写一个如下所示的middleware

some-middleware.js

const actions = {
  [POST_CATEGORIES_SUCCESS]: 1,
  [SET_READING_TIME_SUCCESS]: 1
}

export default store => next => action => {

  // console.log("calling auth middleware", action)

  // Reset any session data before SIGNUP or LOGIN request
  if (actions[action.type] === 1) {
    store.dispatch(resetStories())
    store.dispatch(getStories())
  }


  return next(action)

}

另一种方法是放

    store.dispatch(resetStories())
    store.dispatch(getStories())

里面两个redux-thunk点赞

export const postCategories = (categories) => (dispatch) => {
  dispatch(fetchPostCategories(categories))
  store.dispatch(resetStories())
  store.dispatch(getStories())
}

export const setReadingTime = (readingTime) => (dispatch) => {
  dispatch(fetchReadingTime(readingTime))
  store.dispatch(resetStories())
  store.dispatch(getStories())
}

这意味着每次我需要调度这两个操作时都会重复代码。

我错过了这一切吗?中间件方法是否正确?

【问题讨论】:

    标签: reactjs redux redux-thunk


    【解决方案1】:

    您可以使用 redux-thunk 设置基本调度功能。还有一些额外的代码,如果你有多个动作文件,你需要将函数导入所有文件,但我认为应用程序会更健壮,因为你可能会遇到不想分派这些的情况行动。

    export const baseDispatch = (action) => (dispatch) => {
      dispatch(action)
      dispatch(resetStories())
      dispatch(getStories())
    }
    
    export const postCategories = (categories) => (dispatch) => {
      dispatch(baseDispatch(fetchPostCategories(categories)));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-21
      • 2022-08-21
      • 2017-08-23
      • 2017-04-04
      • 2018-10-14
      • 2016-10-18
      • 2019-04-20
      相关资源
      最近更新 更多