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

后端 未结 1 1776
遥遥无期
遥遥无期 2021-02-05 15:52

I am learning React and following a few tutorials, I came across this code:

import React                  from \'react\';
import TodosView              from \'c         


        
相关标签:
1条回答
  • 2021-02-05 16:10

    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…

    0 讨论(0)
提交回复
热议问题