bindActionCreators(actionCreators, dispatch)
Normally you should just call dispatch
directly on your instance. If you use Redux with React, react-redux will provide you with the function so you can call it directly, too.
The only use case for bindActionCreators
is when you want to pass some action creators down to a component that isn't aware of Redux, and you don't want to pass dispatch
or the Redux store to it.
Parameters
actionCreators
(Function or Object): An action creator, or an object whose values are action creators.dispatch
(Function): A function available on theStore
instance.
Returns
Example
TodoActionCreators.js
SomeComponent.js
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 {
constructor(props) {
super(props)
const { dispatch } = props
// Here's a good use case for bindActionCreators:
// You want a child component to be completely unaware of Redux.
// We create bound versions of these functions now so we can
// pass them down to our child later.
this.boundActionCreators = bindActionCreators(TodoActionCreators, dispatch)
console.log(this.boundActionCreators)
// {
// addTodo: Function,
// removeTodo: Function
// }
}
componentDidMount() {
// Injected by react-redux:
let { dispatch } = this.props
// Note: this won't work:
// TodoActionCreators.addTodo('Use Redux')
// You must dispatch the action, too!
// This will work:
let action = TodoActionCreators.addTodo('Use Redux')
dispatch(action)
}
render() {
// Injected by react-redux:
let { todos } = this.props
return <TodoList todos={todos} {...this.boundActionCreators} />
// An alternative to bindActionCreators is to pass
// just the dispatch function down, but then your child component
// needs to import action creators and know about them.
// return <TodoList todos={todos} dispatch={dispatch} />
}
}
export default connect(state => ({ todos: state.todos }))(TodoListContainer)
Tips
If you use ES5, instead of
import * as
syntax you can just passrequire('./TodoActionCreators')
tobindActionCreators
as the first argument. The only thing it cares about is that the values of theactionCreators
properties are functions. The module system doesn't matter.