Reduxthunk中间件

背景

Redux store 仅支持同步数据流。使用 thunk 等中间件可以帮助在 Redux 应用中实现异步性。可以将 thunk 看做 store 的 dispatch() 方法的封装器;我们可以使用 thunk action creator 派遣函数或 Promise,而不是返回 action 对象。

注意,没有 thunk 的话,默认地是同步派遣。也就是说,我们依然可以从 React 组件发出 API 调用(例如使用 componentDidMount() 生命周期方法发出这些请求),但是我们在 Redux 应用中难以实现以下两点:

  • 可重用性(思考下合成
  • 可预测性,只有 action creator 可以是状态更新的单一数据源

要在应用中使用 thunk 中间件,请务必安装 redux-thunk 软件包

npm install --save redux-thunk

Thunk Action Creator 示例

假设我们要构建一个存储用户代办事项的Web应用。用户登录后,应用需要从数据库中获取用户的所有代办事项。因为 Redux 仅支持同步数据流,我们可以使用 thunk 中间件来异步地生成 Ajax 请求以获取 action。

在能够编写 thunk action creator 之前,确保我们的 store 已准备好接收中间件:

// store.js

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

const store = () => createStore(rootReducer, applyMiddleware(thunk));

export default store;

现在一切设置完毕, thunk 中间件已经能被应用到该 store:thunk 中间件导入自 redux-thunk,并且 thunk 的实例被传递给 Redux 的 applyMiddleware() enhancer函数。

此外,Ajax 请求可以如下所示::

// util/todos_api_util.js

export const fetchTodos = () => fetch('/api/todos');

thunk 中间件使我们能够编写异步 action creator,它返回的是函数,而不是对象。我们的新 action creator 现在可以如下所示:

import * as TodoAPIUtil from '../util/todo_api_util';

export const RECEIVE_TODOS = "RECEIVE_TODOS";

export const receiveTodos = todos => ({
  type: RECEIVE_TODOS,
  todos
});

export const fetchTodos = () => dispatch => (
  TodoAPIUtil
      .fetchTodos()
      .then(todos => dispatch(receiveTodos(todos)))
);

receiveTodos() 是一个 action creator,返回键类型为 RECEIVE_TODOS 的对象以及 todos 载荷。

另一方面,fetchTodos() 使我们能够返回函数。这里,我们首先通过 TodoAPIUtil 发出 Ajax 请求。通过定义一个 Promise 对象,只有当原始请求被解决时 接收所有 to-do 项目的 action 才会被派遣。

现在该你来运用所学的 thunk 知识,对派遣 action 的流程进行修改了!

 
 

总结及更多资料

如果应用需要与服务器交互,则应用 thunk 等中间件可以解决异步数据流问题。Thunk 使我们能够编写返回函数(而不是对象)的 action creator。然后 thunk 可以用来延迟 action 派遣,或仅在满足特定条件(例如请求被解决)后再派遣。

更多资料



作者:StevenQin
链接:https://www.jianshu.com/p/51c8eaa9fa2a
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
原文地址:https://www.cnblogs.com/sexintercourse/p/15689866.html