javascript - Action 必须是普通对象。使用自定义中间件

标签 javascript asynchronous react-native redux-thunk

会出现什么问题?

Uncaught Error: Actions must be plain objects. Use custom middleware for async actions.

配置商店:

export default configureStore = () => {
  let store = compose(applyMiddleware(ReduxThunk))(createStore)(reducers);
  return store;
}

行动

export const menulist = async ({ navigation  }) => {
  return async dispatch => {
    try {
        dispatch({ type: types.MENULIST_REQUEST_START })
        let response = await menuListByCategories();
        dispatch({ type: types.MENULIST_SUCCESS })
    } catch (error) {
        dispatch({ type: types.MENULIST_FAILED })
    }
  }
}

最佳答案

你的使用方式不对

在 Redux 中,每个操作都必须返回一个对象,这是必须的! 所以,你的调度,它是一个函数,应该这样调用。

此外,您只需要声明返回调度的函数 async 即可。 async 关键字决定以下函数将返回一个 Promise。由于您的第一个函数(菜单列表)返回第二个函数(调度函数)返回的 promise ,因此您不必指定它。

export const menulist = ({ navigation  }) => async (dispatch) => {
    try {
        dispatch({ type: types.MENULIST_REQUEST_START })
        let response = await menuListByCategories();

        dispatch({ type: types.MENULIST_SUCCESS })
    } catch (error) {
        dispatch({ type: types.MENULIST_FAILED })
    }
  }
}

关于javascript - Action 必须是普通对象。使用自定义中间件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47139312/

相关文章:

reactjs - React navigation 5 canGoBack() 用于堆栈导航器

react-native - 如何使用 ReactNavigation 判断 View 何时出现

javascript - 捕获/保存/导出应用了 CSS 滤镜效果的图像

javascript - JQuery 应用存储在变量中的 css

javascript - 如何确保 Angular 服务构造函数中的异步初始化完成?

javascript - 执行一系列 Javascript promise ,一个接一个解决

javascript - 防止在键盘 Tab 键时滚动

javascript - animate.css 的滚动效果

c# - Windows 窗体应用程序中的异步显示

react-native - react-Native 上的自定义形状按钮