Redux Cheat Sheet
Redux Cheat Sheet
1)
import React from 'react'
import ReactDOM from 'react-dom'
import { createStore, combineReducers,
applyMiddleware, bindActionCreators } from 'redux'
const greetingReducer = (state='' , action) => {
switch (action.type) {
case 'SAY_HELLO': return 'Hello '
case 'SAY_GOODBYE': return 'Goodbye '
}
return state
}
const nameReducer = (state='John', action) => {
switch (action.type) {
case 'CHANGE_NAME': return 'Joel'
}
return state
}
const actionLogger = ({dispatch, getState}) =>
(next) => (action) =>
{ console.log(action); return next(action) }
const reducers = combineReducers({
greeting: greetingReducer,
name: nameReducer
})
const middleware = applyMiddleware(actionLogger)
const store = createStore(
reducers,
{ greeting: '(Roll over me) '},
middleware
)
const changeName = () => {return { type: 'CHANGE_NAME' }}
const hello = () => {return { type: 'SAY_HELLO' }}
const goodbye = () => {return { type: 'SAY_GOODBYE' }}
const Hello = (props) =>
<div
onMouseOver={props.hello}
onMouseOut={props.goodbye}
onClick={props.changeName}>
{props.greeting}{props.name}
</div>
const render = () => {
ReactDOM.render(
<Hello
greeting={store.getState().greeting}
name={store.getState().name}
{...bindActionCreators({changeName, hello, goodbye},
store.dispatch)}
/>,
document.getElementById('root')
)
}
render()
store.subscribe(render)
Action
) State
Takes the previous state and an action, and returns the next state.
Glossary
State
type State = any
getState}
) next action
combineReducers(
{Reducers}
Action
type Action = {
type:
String ,
payload: any
Reducer
type Reducer<State, Action> = ( State ,
Dispatching Functions
type BaseDispatch = ( Action ) => Action
) Function
Combines multiple reducers into a single reducing function with each reducer as a
key/value pair. Can then be passed to createStore().
Action Creator
type ActionCreator = ( ANY ) => Action | AsyncAction
applyMiddleware(
...middleWares
) Function
Async Action
Extends Redux with custom functionality by wrapping the stores dispatch method.
createStore( Reducer ,
?initialState
?enhancer
) Store
Creates a Redux store that holds the complete state tree of your app.
There should only be a single store in your app.
Middleware
type MiddlewareAPI = {
dispatch:
Dispatch ,
getState:
() => State }
Store
store = { ... }
type Store =
Brings together your application's state and has the following responsibilities:
Store Creator
type StoreCreator = ( Reducer ,
?initialState ,
Store Enhancer
type StoreEnhancer = ( StoreCreator ) => StoreCreator
bindActionCreators( ActionCreators ,
Dispatch
) Fn | Obj
Turns an object whose values are action creators, into an object with the same keys,
but with every action creator wrapped into a dispatch call so they may be invoked
directly.