비공식 베타 번역
이 페이지는 PageTurner AI로 번역되었습니다(베타). 프로젝트 공식 승인을 받지 않았습니다. 오류를 발견하셨나요? 문제 신고 →
bindActionCreators(actionCreators, dispatch)
개요
값이 액션 생성자인 객체를 동일한 키를 가진 새 객체로 변환합니다. 단, 각 액션 생성자는 dispatch 호출로 래핑되어 직접 호출 가능합니다.
일반적으로는 Store 인스턴스에서 직접 dispatch를 호출하면 됩니다. Redux를 React와 함께 사용할 경우 react-redux가 dispatch 함수를 제공하므로 직접 호출할 수도 있습니다.
bindActionCreators는 Redux를 인식하지 않는 컴포넌트에 액션 생성자를 전달하려고 할 때, 그리고 dispatch나 Redux 스토어를 전달하지 않으려는 경우에만 사용합니다.
편의를 위해 첫 번째 인수로 액션 생성자를 단독으로 전달하면 디스패치 래핑된 함수를 반환합니다.
경고
이 기능은 레거시 React-Redux connect 메서드와 함께 사용하기 위해 원래 설계되었습니다. 여전히 동작하지만 거의 필요하지 않습니다.
매개변수
-
actionCreators(함수 또는 객체): 단일 액션 생성자 또는 값이 액션 생성자인 객체.
반환값
(함수 또는 객체): 원본 객체를 모방한 객체. 각 함수는 해당 액션 생성자가 반환한 액션을 즉시 디스패치합니다. 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)