Redux,确保在redux完成后执行调用

时间:2017-02-04 18:52:08

标签: reactjs redux

我打电话给我的一个redux动作:

performAction(updatesomevalue);

我希望在完成上述操作后将状态发送到某处:

sendState(state);

如何链接这些电话?动作没有回调,所以我不能使用这种方法,我想这可能不是这样做的一种简化方法吗?

1 个答案:

答案 0 :(得分:0)

使用redux-thunk执行异步Redux操作

处理异步Redux操作时最简单的解决方案是使用redux-thunk。

redux-thunk的目的是它允许我们将函数作为动作分派(而不是你可能习惯使用的常规旧对象)

为什么我们要调度返回函数的操作?

这个问题可以改为:为什么redux-thunk是一个有用的库?

如果我们可以派遣一个功能。然后可以给这个函数访问redux store api,因此当将来调用该动作时,它可以访问商店的当前状态和调度。访问调度至关重要,因为这意味着此函数可以调度其他redux操作。下面是一个redux thunk动作创建器的示例,它遵循返回函数的redux-thunk签名。

此redux thunk动作创建器调度初始异步操作,例如调用外部api,然后使用该异步api调用的结果更新状态。

然后检索新状态并用于分派其他操作。 为了制作第一个异步api,我们使用isomorphic-fetch库,这是一个基于promise的请求库,这就是为什么我们能够用.then链接fetch,因为调用fetch会返回一个可靠的promise。

import fetch from 'isomorphic-fetch'

// call api then update state and dispatch second sync action
// based on new state
function thunkActionCreator () {
  return (dispatch, getState) => {

    return fetch(`http://www.example.com/api/users/${id}`)
            .then(response => {
              // if request successful dispatch action
              // using response data to change state
              if (response.status !== 200) {
                dispatch(firstAction(response.data))
              }

              // get the new state
              const secondState = getState()

              // use this newState to dispatch a new action
              dispatch(secondAction(secondState))
            })
  }
}

请记住,您需要将redux-thunk添加到中间件链

import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers/index';

// Note: this API requires redux@>=3.1.0
const store = createStore(
  rootReducer,
  applyMiddleware(thunk)
);

由于redux-thunk是一个中间件,它位于中间件链中。当在任何redux应用程序中调度操作时,它会通过完整的中间件链,并且每个中间件都实现一些自定义功能,例如在redux-logger的情况下记录哪个console.logs在应用程序中发生的操作。