I am learning React and following a few tutorials, I came across this code:
import React from 'react';
import TodosView from 'components/TodosView';
import TodosForm from 'components/TodosForm';
import { bindActionCreators } from 'redux';
import * as TodoActions from 'actions/TodoActions';
import { connect } from 'react-redux';
@connect(state => ({ todos: state.todos }))
export default class Home extends React.Component {
render() {
const { todos, dispatch } = this.props;
return (
<div id="todo-list">
<TodosView todos={todos}
{...bindActionCreators(TodoActions, dispatch)} />
<TodosForm
{...bindActionCreators(TodoActions, dispatch)} />
</div>
);
}
}
This is a todo application and this is the main page, it loads 2 more small components
. I understood almost everything but I couldn't get few things:
- What does
connect
do? I know you have to pass 4 params(I couldn't exactly get what are those 4 variables though). - How is the implementation of
@connect
decorator, how the code will look like after transpiling?
Thanks in advance :)
Redux keeps your application's state in a single object called the store.
connect
allows you to connect your React components to your store's state, that is to pass down to them your store's state asprops
.Without the decorator syntax, your component's export would look like
What it does is that it takes your component (here
Home
) and returns a new component that is properly connected to your store.Connected here means : you receive the store's state as
props
, and when this state is updated, this new connected component receives the new props. Connected also mean that you have access to the store'sdispatch
function, which allows you to mutate the store's state.The four arguments are :
mapStateToProps you probably don't want to inject all your store's state in all your connected components. This function allows you to define which state slices you're interested in, or to pass as
props
new data derived from the store's state. You could do something likestate => ({todosCount: state.todos.length})
and theHome
component would receive thetodosCount
propmapDispatchToProps does the same thing for the dispatch function. You could do something like
dispatch => ({markTodoAsCompleted: todoId => dispatch(markTodoAsCompleted(todoId))})
mergeProps allows you to define a custom function to merge the props your component receives, the ones coming from
mapStateToProps
and the ones coming frommapDispatchToProps
options well, some options…