Search code examples
reactjswebpackecmascript-2016

How use connect in react redux


What is preset for webpack to handel connect decorate I tried to run webpack but nothing happened

/*

connect(store)

class App extends React.Component{

}
*/

Solution

  • To use connect() you need to define a special function called mapStateToProps which tells us how to transform the Redux store state into the props. For example, VisibleTodoList needs to calculate todos to pass to the TodoList, so we define a function that filters the state.todos according to the state.visibilityFilter, and use it in its mapStateToProps:

    const getVisibleTodos = (todos, filter) => {
      switch (filter) {
        case 'SHOW_COMPLETED':
          return todos.filter(t => t.completed)
        case 'SHOW_ACTIVE':
          return todos.filter(t => !t.completed)
        case 'SHOW_ALL':
        default:
          return todos
      }
    }
     
    const mapStateToProps = state => {
      return {
        todos: getVisibleTodos(state.todos, state.visibilityFilter)
      }
    }
    

    Now o have to dispatch action to read the state. To do that you can use mapDispatchToProps() function that receives the dispatch() method and returns callback props that you want to inject into the component.

    const mapDispatchToProps = dispatch => {
      return {
        onTodoClick: id => {
          dispatch(toggleTodo(id))
        }
      }
    }
    

    Finally, using VisibleTodoList by calling connect() and passing these two functions:

    import { connect } from 'react-redux'
     
    const VisibleTodoList = connect(
      mapStateToProps,
      mapDispatchToProps
    )(TodoList)
     
    export default VisibleTodoList