Movatterモバイル変換


[0]ホーム

URL:


Skip to main content

 

connect()

tip

connect still works and is supported in React-Redux 8.x. However,we recommend using the hooks API as the default.

Overview

Theconnect() function connects a React component to a Redux store.

It provides its connected component with the pieces of the data it needs from the store, and the functions it can use to dispatch actions to the store.

It does not modify the component class passed to it; instead, it returns a new, connected component class that wraps the component you passed in.

functionconnect(mapStateToProps?, mapDispatchToProps?, mergeProps?, options?)

ThemapStateToProps andmapDispatchToProps deals with your Redux store’sstate anddispatch, respectively.state anddispatch will be supplied to yourmapStateToProps ormapDispatchToProps functions as the first argument.

The returns ofmapStateToProps andmapDispatchToProps are referred to internally asstateProps anddispatchProps, respectively. They will be supplied tomergeProps, if defined, as the first and the second argument, where the third argument will beownProps. The combined result, commonly referred to asmergedProps, will then be supplied to your connected component.

connect() Parameters

connect accepts four different parameters, all optional. By convention, they are called:

  1. mapStateToProps?: Function
  2. mapDispatchToProps?: Function | Object
  3. mergeProps?: Function
  4. options?: Object

mapStateToProps?: (state, ownProps?) => Object

If amapStateToProps function is specified, the new wrapper component will subscribe to Redux store updates. This means that any time the store is updated,mapStateToProps will be called. The results ofmapStateToProps must be a plain object, which will be merged into the wrapped component’s props. If you don't want to subscribe to store updates, passnull orundefined in place ofmapStateToProps.

Parameters

  1. state: Object
  2. ownProps?: Object

AmapStateToProps function takes a maximum of two parameters. The number of declared function parameters (a.k.a. arity) affects when it will be called. This also determines whether the function will receive ownProps. See noteshere.

state

If yourmapStateToProps function is declared as taking one parameter, it will be called whenever the store state changes, and given the store state as the only parameter.

constmapStateToProps=(state)=>({todos: state.todos})
ownProps

If yourmapStateToProps function is declared as taking two parameters, it will be called whenever the store state changesor when the wrapper component receives new props (based on shallow equality comparisons). It will be given the store state as the first parameter, and the wrapper component's props as the second parameter.

The second parameter is normally referred to asownProps by convention.

constmapStateToProps=(state, ownProps)=>({
todo: state.todos[ownProps.id],
})

Returns

YourmapStateToProps functions are expected to return an object. This object, normally referred to asstateProps, will be merged as props to your connected component. If you definemergeProps, it will be supplied as the first parameter tomergeProps.

The return of themapStateToProps determine whether the connected component will re-render (detailshere).

For more details on recommended usage ofmapStateToProps, please refer toour guide on usingmapStateToProps.

You may definemapStateToProps andmapDispatchToProps as a factory function, i.e., you return a function instead of an object. In this case your returned function will be treated as the realmapStateToProps ormapDispatchToProps, and be called in subsequent calls. You may see notes onFactory Functions or our guide on performance optimizations.

mapDispatchToProps?: Object | (dispatch, ownProps?) => Object

Conventionally calledmapDispatchToProps, this second parameter toconnect() may either be an object, a function, or not supplied.

Your component will receivedispatch by default, i.e., when you do not supply a second parameter toconnect():

// do not pass `mapDispatchToProps`
connect()(MyComponent)
connect(mapState)(MyComponent)
connect(mapState,null, mergeProps, options)(MyComponent)

If you define amapDispatchToProps as a function, it will be called with a maximum of two parameters.

Parameters

  1. dispatch: Function
  2. ownProps?: Object
dispatch

If yourmapDispatchToProps is declared as a function taking one parameter, it will be given thedispatch of yourstore.

constmapDispatchToProps=(dispatch)=>{
return{
// dispatching plain actions
increment:()=>dispatch({type:'INCREMENT'}),
decrement:()=>dispatch({type:'DECREMENT'}),
reset:()=>dispatch({type:'RESET'}),
}
}
ownProps

If yourmapDispatchToProps function is declared as taking two parameters, it will be called withdispatch as the first parameter and the props passed to the wrapper component as the second parameter, and will be re-invoked whenever the connected component receives new props.

The second parameter is normally referred to asownProps by convention.

// binds on component re-rendering
<button onClick={()=>this.props.toggleTodo(this.props.todoId)}/>

// binds on `props` change
constmapDispatchToProps=(dispatch, ownProps)=>({
toggleTodo:()=>dispatch(toggleTodo(ownProps.todoId)),
})

The number of declared function parameters ofmapDispatchToProps determines whether they receive ownProps. See noteshere.

Returns

YourmapDispatchToProps functions are expected to return an object. Each fields of the object should be a function, calling which is expected to dispatch an action to the store.

The return of yourmapDispatchToProps functions are regarded asdispatchProps. It will be merged as props to your connected component. If you definemergeProps, it will be supplied as the second parameter tomergeProps.

constcreateMyAction=()=>({type:'MY_ACTION'})
constmapDispatchToProps=(dispatch, ownProps)=>{
const boundActions=bindActionCreators({ createMyAction}, dispatch)
return{
dispatchPlainObject:()=>dispatch({type:'MY_ACTION'}),
dispatchActionCreatedByActionCreator:()=>dispatch(createMyAction()),
...boundActions,
// you may return dispatch here
dispatch,
}
}

For more details on recommended usage, please refer toour guide on usingmapDispatchToProps.

You may definemapStateToProps andmapDispatchToProps as a factory function, i.e., you return a function instead of an object. In this case your returned function will be treated as the realmapStateToProps ormapDispatchToProps, and be called in subsequent calls. You may see notes onFactory Functions or our guide on performance optimizations.

Object Shorthand Form

mapDispatchToProps may be an object where each field is anaction creator.

import{ addTodo, deleteTodo, toggleTodo}from'./actionCreators'

const mapDispatchToProps={
addTodo,
deleteTodo,
toggleTodo,
}

exportdefaultconnect(null, mapDispatchToProps)(TodoApp)

In this case, React-Redux binds thedispatch of your store to each of the action creators usingbindActionCreators. The result will be regarded asdispatchProps, which will be either directly merged to your connected components, or supplied tomergeProps as the second argument.

// internally, React-Redux calls bindActionCreators
// to bind the action creators to the dispatch of your store
bindActionCreators(mapDispatchToProps, dispatch)

We also have a section in ourmapDispatchToProps guide on the usage of object shorthand formhere.

mergeProps?: (stateProps, dispatchProps, ownProps) => Object

If specified, defines how the final props for your own wrapped component are determined. If you do not providemergeProps, your wrapped component receives{ ...ownProps, ...stateProps, ...dispatchProps } by default.

Parameters

mergeProps should be specified with maximum of three parameters. They are the result ofmapStateToProps(),mapDispatchToProps(), and the wrapper component'sprops, respectively:

  1. stateProps
  2. dispatchProps
  3. ownProps

The fields in the plain object you return from it will be used as the props for the wrapped component. You may specify this function to select a slice of the state based on props, or to bind action creators to a particular variable from props.

Returns

The return value ofmergeProps is referred to asmergedProps and the fields will be used as the props for the wrapped component.

Note: Creating new values in mergeProps will cause re-renders. It is recommended that you memoize fields in order to avoid unnecessary re-renders.

options?: Object

{
context?:Object,
areStatesEqual?:Function,
areOwnPropsEqual?:Function,
areStatePropsEqual?:Function,
areMergedPropsEqual?:Function,
forwardRef?: boolean,
}

context: Object

Note: This parameter is supported in >= v6.0 only

React-Redux v6 allows you to supply a custom context instance to be used by React-Redux.You need to pass the instance of your context to both<Provider /> and your connected component.You may pass the context to your connected component either by passing it here as a field of option, or as a prop to your connected component in rendering.

// const MyContext = React.createContext();
connect(mapStateToProps, mapDispatchToProps,null,{context:MyContext})(
MyComponent,
)

areStatesEqual: (next: Object, prev: Object, nextOwnProps: Object, prevOwnProps: Object) => boolean

  • default value:strictEqual: (next, prev) => prev === next

Compares incoming store state to its previous value.

constareStatesEqual=(next, prev)=>
prev.entities.todos=== next.entities.todos

You may wish to overrideareStatesEqual if yourmapStateToProps function is computationally expensive and is also only concerned with a small slice of your state. The example above will effectively ignore state changes for everything but that slice of state. Additionally,areStatesEqual providesnextOwnProps andprevOwnProps to allow for more effective scoping of your state which your connected component is interested in, if needed.

This would likely impact the other equality checks as well, depending on yourmapStateToProps function.

areOwnPropsEqual: (next: Object, prev: Object) => boolean

  • default value:shallowEqual: (objA, objB) => boolean( returnstrue when each field of the objects is equal )

Compares incoming props to its previous value.

You may wish to overrideareOwnPropsEqual as a way to whitelist incoming props. You'd also have to implementmapStateToProps,mapDispatchToProps andmergeProps to also whitelist props. (It may be simpler to achieve this other ways, for example by usingrecompose's mapProps.)

areStatePropsEqual: (next: Object, prev: Object) => boolean

  • type:function
  • default value:shallowEqual

Compares the result ofmapStateToProps to its previous value.

areMergedPropsEqual: (next: Object, prev: Object) => boolean

  • default value:shallowEqual

Compares the result ofmergeProps to its previous value.

You may wish to overrideareStatePropsEqual to usestrictEqual if yourmapStateToProps uses a memoized selector that will only return a new object if a relevant prop has changed. This would be a very slight performance improvement, since would avoid extra equality checks on individual props each timemapStateToProps is called.

You may wish to overrideareMergedPropsEqual to implement adeepEqual if your selectors produce complex props. ex: nested objects, new arrays, etc. (The deep equal check may be faster than just re-rendering.)

forwardRef: boolean

Note: This parameter is supported in >= v6.0 only

If{forwardRef : true} has been passed toconnect, adding a ref to the connected wrapper component will actually return the instance of the wrapped component.

connect() Returns

The return ofconnect() is a wrapper function that takes your component and returns a wrapper component with the additional props it injects.

import{ login, logout}from'./actionCreators'

constmapState=(state)=> state.user
const mapDispatch={ login, logout}

// first call: returns a hoc that you can use to wrap any component
const connectUser=connect(mapState, mapDispatch)

// second call: returns the wrapper component with mergedProps
// you may use the hoc to enable different components to get the same behavior
constConnectedUserLogin=connectUser(Login)
constConnectedUserProfile=connectUser(Profile)

In most cases, the wrapper function will be called right away, without being saved in a temporary variable:

import{ login, logout}from'./actionCreators'

constmapState=(state)=> state.user
const mapDispatch={ login, logout}

// call connect to generate the wrapper function, and immediately call
// the wrapper function to generate the final wrapper component.

exportdefaultconnect(mapState, mapDispatch)(Login)

Example Usage

Becauseconnect is so flexible, it may help to see some additional examples of how it can be called:

  • Inject justdispatch and don't listen to store
exportdefaultconnect()(TodoApp)
  • Inject all action creators (addTodo,completeTodo, ...) without subscribing to the store
import*as actionCreatorsfrom'./actionCreators'

exportdefaultconnect(null, actionCreators)(TodoApp)
  • Injectdispatch and every field in the global state

Don’t do this! It kills any performance optimizations becauseTodoApp will rerender after every state change.It’s better to have more granularconnect() on several components in your view hierarchy that each only listen to a relevant slice of the state.

// don't do this!
exportdefaultconnect((state)=> state)(TodoApp)
  • Injectdispatch andtodos
functionmapStateToProps(state){
return{todos: state.todos}
}

exportdefaultconnect(mapStateToProps)(TodoApp)
  • Injecttodos and all action creators
import*as actionCreatorsfrom'./actionCreators'

functionmapStateToProps(state){
return{todos: state.todos}
}

exportdefaultconnect(mapStateToProps, actionCreators)(TodoApp)
  • Injecttodos and all action creators (addTodo,completeTodo, ...) asactions
import*as actionCreatorsfrom'./actionCreators'
import{ bindActionCreators}from'redux'

functionmapStateToProps(state){
return{todos: state.todos}
}

functionmapDispatchToProps(dispatch){
return{actions:bindActionCreators(actionCreators, dispatch)}
}

exportdefaultconnect(mapStateToProps, mapDispatchToProps)(TodoApp)
  • Injecttodos and a specific action creator (addTodo)
import{ addTodo}from'./actionCreators'
import{ bindActionCreators}from'redux'

functionmapStateToProps(state){
return{todos: state.todos}
}

functionmapDispatchToProps(dispatch){
returnbindActionCreators({ addTodo}, dispatch)
}

exportdefaultconnect(mapStateToProps, mapDispatchToProps)(TodoApp)
  • Injecttodos and specific action creators (addTodo anddeleteTodo) with shorthand syntax
import{ addTodo, deleteTodo}from'./actionCreators'

functionmapStateToProps(state){
return{todos: state.todos}
}

const mapDispatchToProps={
addTodo,
deleteTodo,
}

exportdefaultconnect(mapStateToProps, mapDispatchToProps)(TodoApp)
  • Injecttodos,todoActionCreators astodoActions, andcounterActionCreators ascounterActions
import*as todoActionCreatorsfrom'./todoActionCreators'
import*as counterActionCreatorsfrom'./counterActionCreators'
import{ bindActionCreators}from'redux'

functionmapStateToProps(state){
return{todos: state.todos}
}

functionmapDispatchToProps(dispatch){
return{
todoActions:bindActionCreators(todoActionCreators, dispatch),
counterActions:bindActionCreators(counterActionCreators, dispatch),
}
}

exportdefaultconnect(mapStateToProps, mapDispatchToProps)(TodoApp)
  • Injecttodos, and todoActionCreators and counterActionCreators together asactions
import*as todoActionCreatorsfrom'./todoActionCreators'
import*as counterActionCreatorsfrom'./counterActionCreators'
import{ bindActionCreators}from'redux'

functionmapStateToProps(state){
return{todos: state.todos}
}

functionmapDispatchToProps(dispatch){
return{
actions:bindActionCreators(
{...todoActionCreators,...counterActionCreators},
dispatch,
),
}
}

exportdefaultconnect(mapStateToProps, mapDispatchToProps)(TodoApp)
  • Injecttodos, and alltodoActionCreators andcounterActionCreators directly as props
import*as todoActionCreatorsfrom'./todoActionCreators'
import*as counterActionCreatorsfrom'./counterActionCreators'
import{ bindActionCreators}from'redux'

functionmapStateToProps(state){
return{todos: state.todos}
}

functionmapDispatchToProps(dispatch){
returnbindActionCreators(
{...todoActionCreators,...counterActionCreators},
dispatch,
)
}

exportdefaultconnect(mapStateToProps, mapDispatchToProps)(TodoApp)
  • Injecttodos of a specific user depending on props
import*as actionCreatorsfrom'./actionCreators'

functionmapStateToProps(state, ownProps){
return{todos: state.todos[ownProps.userId]}
}

exportdefaultconnect(mapStateToProps)(TodoApp)
  • Injecttodos of a specific user depending on props, and injectprops.userId into the action
import*as actionCreatorsfrom'./actionCreators'

functionmapStateToProps(state){
return{todos: state.todos}
}

functionmergeProps(stateProps, dispatchProps, ownProps){
returnObject.assign({}, ownProps,{
todos: stateProps.todos[ownProps.userId],
addTodo:(text)=> dispatchProps.addTodo(ownProps.userId, text),
})
}

exportdefaultconnect(mapStateToProps, actionCreators, mergeProps)(TodoApp)

Notes

The Arity ofmapToProps Functions

The number of declared function parameters ofmapStateToProps andmapDispatchToProps determines whether they receiveownProps

Note:ownProps is not passed tomapStateToProps andmapDispatchToProps if the formal definition of the function contains one mandatory parameter (function has length 1). For example, functions defined like below won't receiveownProps as the second argument. If the incoming value ofownProps isundefined, the default argument value will be used.

functionmapStateToProps(state){
console.log(state)// state
console.log(arguments[1])// undefined
}

constmapStateToProps=(state, ownProps={})=>{
console.log(state)// state
console.log(ownProps)// {}
}

Functions with no mandatory parameters or two parameters*will receiveownProps.

constmapStateToProps=(state, ownProps)=>{
console.log(state)// state
console.log(ownProps)// ownProps
}

functionmapStateToProps(){
console.log(arguments[0])// state
console.log(arguments[1])// ownProps
}

constmapStateToProps=(...args)=>{
console.log(args[0])// state
console.log(args[1])// ownProps
}

Factory Functions

If yourmapStateToProps ormapDispatchToProps functions return a function, they will be called once when the component instantiates, and their returns will be used as the actualmapStateToProps,mapDispatchToProps, functions respectively, in their subsequent calls.

The factory functions are commonly used with memoized selectors. This gives you the ability to create component-instance-specific selectors inside the closure:

constmakeUniqueSelectorInstance=()=>
createSelector([selectItems, selectItemId],(items, itemId)=> items[itemId])
constmakeMapState=(state)=>{
const selectItemForThisComponent=makeUniqueSelectorInstance()
returnfunctionrealMapState(state, ownProps){
const item=selectItemForThisComponent(state, ownProps.itemId)
return{ item}
}
}
exportdefaultconnect(makeMapState)(SomeComponent)

Legacy Version Docs

While theconnect API has stayed almost entirely API-compatible between all of our major versions, there have been some small changes in options and behavior from version to version.

For details on the legacy 5.x and 6.x versions, please see these archived files in the React Redux repo:


[8]ページ先頭

©2009-2025 Movatter.jp