React-Native开发从入门到实战项目总结React Native开发React Native开发经验集

redux框架之bindActionCreators()

2017-11-22  本文已影响280人  光强_上海

bindActionCreators

参数

返回值

示例

TodoActionCreators.js

export function addTodo(text) {
  return {
    type: 'ADD_TODO',
    text
  };
}

export function removeTodo(id) {
  return {
    type: 'REMOVE_TODO',
    id
  };
}
import { Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';

import * as TodoActionCreators from './TodoActionCreators';
console.log(TodoActionCreators);
// {
//   addTodo: Function,
//   removeTodo: Function
// }

class TodoListContainer extends Component {
  componentDidMount() {
    // 由 react-redux 注入:
    let { dispatch } = this.props;

    // 注意:这样做行不通:
    // TodoActionCreators.addTodo('Use Redux');

    // 你只是调用了创建 action 的方法。
    // 你必须要 dispatch action 而已。

    // 这样做行得通:
    let action = TodoActionCreators.addTodo('Use Redux');
    dispatch(action);
  }

  render() {
    // 由 react-redux 注入:
    let { todos, dispatch } = this.props;

    // 这是应用 bindActionCreators 比较好的场景:
    // 在子组件里,可以完全不知道 Redux 的存在。

    let boundActionCreators = bindActionCreators(TodoActionCreators, dispatch);
    console.log(boundActionCreators);
    // {
    //   addTodo: Function,
    //   removeTodo: Function
    // }

    return (
      <TodoList todos={todos}
                {...boundActionCreators} />
    );

    // 一种可以替换 bindActionCreators 的做法是直接把 dispatch 函数
    // 和 action creators 当作 props 
    // 传递给子组件
    // return <TodoList todos={todos} dispatch={dispatch} />;
  }
}

export default connect(
  state => ({ todos: state.todos })
)(TodoListContainer)

你或许要问:为什么不直接把 action creators 绑定到 store 实例上,就像传统 Flux 那样?问题是这样做的话如果开发同构应用,在服务端渲染时就不行了。多数情况下,你 每个请求都需要一个独立的 store 实例,这样你可以为它们提供不同的数据,但是在定义的时候绑定 action creators,你就可以使用一个唯一的 store 实例来对应所有请求了。

如果你使用 ES5,不能使用 import * as 语法,你可以把 require('./TodoActionCreators') 作为第一个参数传给 bindActionCreators。惟一要考虑的是 actionCreators 的参数全是函数。模块加载系统并不重要。

福利时间

上一篇下一篇

猜你喜欢

热点阅读