React-Redux

React Components

  • Presentation components
  • Container components

Presentation

  • Get data from this.props
  • Handle event by callbacks
  • Representation of the UI

Container

  • Manipulates the data
  • Handles the event

Redux

  • Action
  • Reducer
  • Store
  • react-redux

Action

  • Information about updating the state
  • Describes what happened
  • Pure javascript object

Action

{
  type: ADD_TODO,
  text: 'Build my first Redux app'
}

{
  type: COMPLETE_TODO,
  index: 5
}

Action Creator

function addTodo(text) {
  return {
    type: ADD_TODO,
    text
  }
}

Reducer

  • Defines how state changes when a action comes
  • Pure function
function (currentState, action) {
    //...
    return newState
}

Don't 

  • Mutate its arguments
  • Perform side effects
  • like API calls and routing transitions

Reducer

// ES6 default arguments syntax
function reducer(state = initialState, action) {
  switch (action.type) {
    case SET_VISIBILITY_FILTER:
      return Object.assign({}, state, {
        visibilityFilter: action.filter
      })
    default:
      return state
  }
}

Reducer

  • We don’t mutate the state
  • Create a copy with Object.assign()
  • Return the previous state in the default case

Splitting Reducers

function doSomething(state, action) {
}

function doSomethingElse(state, action) {
}

function reducer(state, action) {
    a: doSomething(state, action),
    b: doSonethingElse(state, action)
}

//or

var reducer = combineReducers({
    a: doSomething,
    b: doSonethingElse
})

Store

Create a Store

import { createStore } from 'redux'
import reducer from './reducers'
let store = createStore(reducer)

Dispatching Actions

// Log the initial state
console.log(store.getState())

// Every time the state changes, log it
// Note that subscribe() returns a function for unregistering the listener
let unsubscribe = store.subscribe(() =>
  console.log(store.getState())
)

// Dispatch some actions
store.dispatch(addTodo('Learn about actions'))
store.dispatch(addTodo('Learn about reducers'))
store.dispatch(addTodo('Learn about store'))
store.dispatch(completeTodo(0))
store.dispatch(completeTodo(1))
store.dispatch(setVisibilityFilter(VisibilityFilters.SHOW_COMPLETED))

// Stop listening to state updates
unsubscribe()

react-redux

connect()

mapStateToProps = (state) => {
    return {
        a: state.something
    }
}

mapDispatchToProps = (dispatch) => {
    return {
        onClick: (id) => {
            dispatch(action(id))
        }
    }
}


wrappedCompoent = connect(mapStateToProps, mapDispatchToProps)(component)
Made with Slides.com