Connect Function
The connect
function is used for transforming "regular" React components so the state of the Redux store can be "mapped" into the component's props.
- transform Notees component into connected component
- function accepts
mapStateToProps
function as its first parameter- used for defining the props of the connected component based on the state of the Redux store
- notes component has "direct access" via props.notes and props.filter to state in the Redux store
- function accepts
mapDispatchToProps
as second parameter- group of action creator functions passed to the connected component as props
- [Mapdispatchtoprops Alternative Definition]
Example usage of connect
function
import React from 'react'import { connect } from 'react-redux' import { toggleImportanceOf } from '../reducers/noteReducer'const Notes = (props) => { return( <ul> {props.notes.map(note => <Note key={note.id} note={note} handleClick={() => props.toggleImportanceOf(note.id)} /> )} </ul> )}const mapStateToProps = (state) => { if ( state.filter === 'ALL' ) { return { notes: state.notes } } return { notes: (state.filter === 'IMPORTANT' ? state.notes.filter(note => note.important) : state.notes.filter(note => !note.important) ) }}const mapDispatchToProps = { toggleImportanceOf}export default connect( mapStateToProps, mapDispatchToProps)(Notes)
Source -> Redux: connect function