【问题标题】:React hook - dispatch an async await action in another fileReact hook - 在另一个文件中调度异步等待操作
【发布时间】:2020-04-29 22:26:49
【问题描述】:

例如,我有一个方法会调度类似的动作

// index.js
export default class PageNavigation {
    export async switchPage(pageId) {
      return async (dispatch) => {
          await dispatch(selectPage({ pageId }));
          await dispatch(changeTitle({ pageId }));
          //... more dispatch
    };
    function selectPage(id) {
       return async (dispatch, getState) => {
         //await some complex logic involve some other dispatch
       }
    };
    function changeTitle(id) {
       return async (dispatch, getState) => {
         //await some complex logic involve some other dispatch
       }
    };
}

现在我有一个使用useDispatch() 钩子的反应钩子组件,我想使用dispatch 钩子调用上面的switchPage 方法,我尝试了以下方法,但它们都不起作用:

const PageManagement = (props) => {
   const dispatch = useDispatch();
   // Try 1: the 'dispatch' inside switchPage didn't get fired, seems the dispatch here is undefined?
   await switchPage('640');
   // Try 2: Global Unhandled Promise Rejection Error: Actions must be plain objects. 
   // Use custom middleware for async actions.
   dispatch(switchPage('640'));
}

实现上述场景的正确方法是什么?我知道下面可以通过使用dispatch 直接调用操作来工作,但这不是我想要的,因为一旦有更多操作,似乎每个操作都需要一个一个地调度?

await dispatch(selectPage('640'));
await dispatch(changeTitle('640'));
// ... keep calling other dispatch in component?

【问题讨论】:

    标签: reactjs react-redux react-hooks


    【解决方案1】:

    也许您应该提供dispatch 作为参数:

    export async switchPage(dispatch, pageId) {
              await dispatch(selectPage({ pageId }));
              await dispatch(changeTitle({ pageId }));
        };
    

    然后在你的组件中这样调用它:

    const dispatch = useDispatch();
    await switchPage(dispatch, '640');
    

    【讨论】:

      猜你喜欢
      • 2018-10-22
      • 2015-11-09
      • 2022-06-29
      • 2021-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多