Redux API之bindActionCreators

时间:2016-03-15 17:14:55   收藏:0   阅读:726

bindActionCreators(actionCreators,dispatch)

把 action creators 转成拥有同名 keys 的对象,但使用 dispatch 把每个 action creator 包围起来,这样可以直接调用它们。

一般情况下你可以直接在 Store 实例上调用 dispatch。如果你在 React 中使用 Redux,react-redux 会提供 dispatch 。

惟一使用 bindActionCreators 的场景是当你需要把 action creator 往下传到一个组件上,却不想让这个组件觉察到 Redux 的存在,而且不希望把 Redux store 或 dispatch 传给它。

为方便起见,你可以传入一个函数作为第一个参数,它会返回一个函数。

参数

  1. actionCreators (Function or Object): 一个 action creator,或者键值是 action creators 的对象。

  2. dispatch (Function): 一个 dispatch 函数,由 Store 实例提供。

返回值

(Function or Object): 一个与原对象类似的对象,只不过这个对象中的的每个函数值都可以直接 dispatch action。如果传入的是一个函数,返回的也是一个函数。

示例

技术分享
 1 TodoActionCreators.js
 2 
 3 export function addTodo(text) {
 4   return {
 5     type: ‘ADD_TODO‘,
 6     text
 7   };
 8 }
 9 
10 export function removeTodo(id) {
11   return {
12     type: ‘REMOVE_TODO‘,
13     id
14   };
15 }
16 SomeComponent.js
17 
18 import { Component } from ‘react‘;
19 import { bindActionCreators } from ‘redux‘;
20 import { connect } from ‘react-redux‘;
21 
22 import * as TodoActionCreators from ‘./TodoActionCreators‘;
23 console.log(TodoActionCreators);
24 // {
25 //   addTodo: Function,
26 //   removeTodo: Function
27 // }
28 
29 class TodoListContainer extends Component {
30   componentDidMount() {
31     // 由 react-redux 注入:
32     let { dispatch } = this.props;
33 
34     // 注意:这样做行不通:
35     // TodoActionCreators.addTodo(‘Use Redux‘);
36 
37     // 你只是调用了创建 action 的方法。
38     // 你必须要 dispatch action 而已。
39 
40     // 这样做行得通:
41     let action = TodoActionCreators.addTodo(‘Use Redux‘);
42     dispatch(action);
43   }
44 
45   render() {
46     // 由 react-redux 注入:
47     let { todos, dispatch } = this.props;
48 
49     // 这是应用 bindActionCreators 比较好的场景:
50     // 在子组件里,可以完全不知道 Redux 的存在。
51 
52     let boundActionCreators = bindActionCreators(TodoActionCreators, dispatch);
53     console.log(boundActionCreators);
54     // {
55     //   addTodo: Function,
56     //   removeTodo: Function
57     // }
58 
59     return (
60       <TodoList todos={todos}
61                 {...boundActionCreators} />
62     );
63 
64     // 一种可以替换 bindActionCreators 的做法是直接把 dispatch 函数
65     // 和 action creators 当作 props 
66     // 传递给子组件
67     // return <TodoList todos={todos} dispatch={dispatch} />;
68   }
69 }
70 
71 export default connect(
72   state => ({ todos: state.todos })
73 )(TodoListContainer)
View Code

小贴士

原文:http://www.cnblogs.com/ZSG-DoBestMe/p/5280198.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!