What is the use of @connect decorator in react-red

2019-03-15 08:18发布

问题:

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 :)

回答1:

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 as props.

Without the decorator syntax, your component's export would look like

export default connect(state => ({todos: state.todos}))(Home);

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's dispatch 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 like state => ({todosCount: state.todos.length}) and the Home component would receive the todosCount prop

  • mapDispatchToProps 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 from mapDispatchToProps

  • options well, some options…