首页 > 解决方案 > 在 React 中完成一个动作后调用另一个动作

问题描述

我正在使用 Redux Thunk。

我有一个异步操作(将消息更新到数据库),我想等待它完成,然后从数据库中获取更新的消息数组。

我试过了:

const handleWriteMessage = async (e) => {
e.preventDefault()

await dispatch(
  writeMessage({
    sender: data.sender,
    subject: data.subject,
    receiver: data.receiver,
    message: data.message,
    created: date
  })
)
dispatch(getMessages())
}

但它不介意awaitand在被调用getMessages()时立即运行。handleWriteMessage完成后,我尝试在动作本身中执行此操作:

axios
.post('http://localhost:4000/api/messages/writeMessage', msg, config)
.then((res) => {
  getMessages()
  dispatch({
    type: WRITE_MESSAGE_SUCCESS
  })
})

但它也不起作用。

我错过了什么?

标签: javascriptreactjsredux

解决方案


似乎不handleWriteMessage应该async,它必须返回将接受dispatch并可能执行async函数的函数,请参阅 redux-thunk文档

请参阅下面的代码段及其输出。

var thunk = createThunkMiddleware();
var log = (state = [], action) => state.concat(action.message || action.type);
var store = Redux.createStore(log, [], Redux.applyMiddleware(thunk, logger));

(async() => {
  store.dispatch(asyncAC('async message 1.a'))
    .then(() => asyncAC('async message 1.b'))
    .then(store.dispatch);

  store.dispatch(syncAC('sync 1'));

  await store.dispatch(asyncAC('await async message 2.a'));

  store.dispatch(syncAC('sync 2'));

  store.dispatch(asyncAC('await async message 3.a'))
    .then(() => store.dispatch(asyncAC('then async message 3.b')));

})();

function syncAC(m) {
  return {
    type: 'log',
    message: m
  }
}

function asyncAC(m) {
  return (dispatch) => {
    return new Promise(resolve => setTimeout(resolve, 1000, syncAC(m)))
      .then(dispatch);
  }
}




// redux-thunk itself
function createThunkMiddleware(extraArgument) {
  return function(_ref) {
    var dispatch = _ref.dispatch,
      getState = _ref.getState;
    return function(next) {
      return function(action) {
        if (typeof action === 'function') {
          return action(dispatch, getState, extraArgument);
        }

        return next(action);
      };
    };
  };
}
// logger middleware
function logger({
  getState
}) {
  return next => action => {
    console.log('will dispatch', action)

    // Call the next dispatch method in the middleware chain.
    const returnValue = next(action)

    console.log('state after dispatch', getState())

    // This will likely be the action itself, unless
    // a middleware further in chain changed it.
    return returnValue
  }
}
<script src="https://unpkg.com/redux@4.0.5/dist/redux.js"></script>


推荐阅读