mapStateToProps
, mapDispatchToProps
and connect
from react-redux
library provides a convenient way to access your state
and dispatch
function of your store. So basically connect is a higher order component, you can also think as a wrapper if this make sense for you. So every time your state
is changed mapStateToProps
will be called with your new state
and subsequently as you props
update component will run render function to render your component in browser. mapDispatchToProps
also stores key-values on the props
of your component, usually they take a form of a function. In such way you can trigger state
change from your component onClick
, onChange
events.
From docs:
const TodoListComponent = ({ todos, onTodoClick }) => (
<ul>
{todos.map(todo =>
<Todo
key={todo.id}
{...todo}
onClick={() => onTodoClick(todo.id)}
/>
)}
</ul>
)
const mapStateToProps = (state) => {
return {
todos: getVisibleTodos(state.todos, state.visibilityFilter)
}
}
const mapDispatchToProps = (dispatch) => {
return {
onTodoClick: (id) => {
dispatch(toggleTodo(id))
}
}
}
function toggleTodo(index) {
return { type: TOGGLE_TODO, index }
}
const TodoList = connect(
mapStateToProps,
mapDispatchToProps
)(TodoList)
Also make sure that you are familiar with React stateless functions and Higher-Order Components