跳至主内容
非官方测试版翻译

本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →

bindActionCreators(actionCreators, dispatch)

概述

将一个值都是动作创建函数的对象,转换为具有相同键的对象,但每个动作创建函数都被包装进dispatch调用中,从而可以直接调用它们。

通常你应该直接在Store实例上调用dispatch。如果在 React 中使用 Redux,react-redux 会提供dispatch函数让你也能直接调用。

bindActionCreators 的唯一使用场景是:当你需要向不了解 Redux 的组件传递某些动作创建函数,且不希望传递dispatch或 Redux store 时。

为方便起见,你也可以将单个动作创建函数作为第一个参数传入,将获得一个被 dispatch 包装的函数作为返回值。

警告

该方法最初设计用于旧版 React-Redux 的 connect 方法。它仍然有效,但很少需要。

参数

  1. actionCreators (函数对象): 一个动作创建函数,或其值都是动作创建函数的对象。

  2. dispatch (函数): 来自Store实例的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)