bindActionCreators(actionCreators, dispatch)
概述
將值為 動作建立器 的物件,轉換為具有相同金鑰的物件,但每個動作建立器都封裝在 dispatch
呼叫中,以便直接呼叫它們。
通常,您應該直接在 dispatch
上呼叫 Store
執行個體。如果您將 Redux 與 React 搭配使用,react-redux 會提供 dispatch
函數,因此您也可以直接呼叫它。
bindActionCreators
的唯一使用案例是當您想要將一些動作建立函數傳遞給不了解 Redux 的元件時,而且您不想傳遞 dispatch
或 Redux 儲存給它。
為方便起見,您也可以將動作建立函數傳遞為第一個引數,並取得一個封裝 dispatch 的函數作為回傳值。
警告
這原本是打算與舊版 React-Redux connect
方法搭配使用。它仍然有效,但很少需要使用。
參數
回傳值
(函數 或 物件):模仿原始物件的物件,但每個函數會立即 dispatch 對應動作建立函數回傳的動作。如果您傳遞函數作為 actionCreators
,回傳值也會是單一函數。
範例
TodoActionCreators.js
export function addTodo(text) {
return {
type: 'ADD_TODO',
text
}
}
export function removeTodo(id) {
return {
type: 'REMOVE_TODO',
id
}
}
SomeComponent.js
import React from 'react'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import * as TodoActionCreators from './TodoActionCreators'
console.log(TodoActionCreators)
// {
// addTodo: Function,
// removeTodo: Function
// }
function TodoListContainer(props) {
// Injected by react-redux:
const { dispatch, todos } = 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.
const boundActionCreators = useMemo(
() => bindActionCreators(TodoActionCreators, dispatch),
[dispatch]
)
console.log(boundActionCreators)
// {
// addTodo: Function,
// removeTodo: Function
// }
useEffect(() => {
// Note: this won't work:
// TodoActionCreators.addTodo('Use Redux')
// You're just calling a function that creates an action.
// You must dispatch the action, too!
// This will work:
let action = TodoActionCreators.addTodo('Use Redux')
dispatch(action)
}, [])
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)