Movatterモバイル変換


[0]ホーム

URL:


Skip to main content

 

bindActionCreators(actionCreators, dispatch)

Overview

Turns an object whose values areaction creators, into an object with the same keys, but with every action creator wrapped into adispatch call so they may be invoked directly.

Normally you should just calldispatch directly on yourStore instance. If you use Redux with React,react-redux will provide you with thedispatch function so you can call it directly, too.

The only use case forbindActionCreators 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 passdispatch or the Redux store to it.

For convenience, you can also pass an action creator as the first argument, and get a dispatch wrapped function in return.

Warning

This was originally intended for use with the legacy React-Reduxconnect method. It still works, but is rarely needed.

Parameters

  1. actionCreators (Function orObject): Anaction creator, or an object whose values are action creators.

  2. dispatch (Function): Adispatch function available on theStore instance.

Returns

(Function orObject): An object mimicking the original object, but with each function immediately dispatching the action returned by the corresponding action creator. If you passed a function asactionCreators, the return value will also be a single function.

Example

TodoActionCreators.js

exportfunctionaddTodo(text){
return{
type:'ADD_TODO',
text
}
}

exportfunctionremoveTodo(id){
return{
type:'REMOVE_TODO',
id
}
}

SomeComponent.js

importReactfrom'react'
import{ bindActionCreators}from'redux'
import{ connect}from'react-redux'

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

functionTodoListContainer(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} />
}

exportdefaultconnect(state=>({todos: state.todos}))(TodoListContainer)

[8]ページ先頭

©2009-2025 Movatter.jp