Created
February 8, 2017 17:48
-
-
Save jpalala/13a2536a5d4251ab26cb52145bdcd7ad to your computer and use it in GitHub Desktop.
React+Redux cheat sheet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ************************************** redux ********************************************** | |
import { applyMiddleware, createStore } from 'redux'; | |
const reducer = (state, action) => { | |
switch (action.type) { | |
case 'FOO': { return action.bar; } | |
}; | |
return state; | |
}; | |
const store = createStore(reducer); // or... | |
const store = createStore(reducer, initialState); // or... | |
const store = createStore(reducer, initialState, applyMiddleware(sagaMiddleware)); | |
// ************************* react-redux ****************************** | |
import React from 'react' | |
import ReactDOM from 'react-dom'; | |
import { Provider, connect } from 'react-redux' | |
const mapStateToProps = state => ({foo: state.foo}); // or... | |
const mapStateToProps = (state, props) => ({foo: state.foo + props.bar}); | |
const mapDispatchToProps = dispatch => ({launch: (target) => dispatch({type: 'LAUNCH', to: target})); // or... | |
const mapDispatchToProps = (dispatch, props) => ({launch: () => dispatch({type: 'LAUNCH', to: props.target})); | |
class LauncherClass extends React.Component { | |
render() { | |
return <a href="#" onClick={this.props.launch}>{this.props.foo}</a> | |
} | |
} | |
const Launcher = connect(mapStateToProps, mapDispatchToProps)(LauncherClass); | |
ReactDOM.render( | |
<Provider store={store}> | |
<Launcher target={"moon"}/> | |
</Provider>, | |
document.getElementById('root') | |
) | |
// ************************************** redux-saga ********************************************* | |
import 'babel-polyfill'; // need for generators | |
import createSagaMiddleware, { takeEvery, delay } from 'redux-saga'; | |
import { call, put } from 'redux-saga/effects'; | |
function* delayAndThenPush(action) { | |
yield call(delay, action.delay); | |
yield put({type: 'PUSH', msg: action.msg}); | |
}; | |
function* mySaga() { | |
yield* takeEvery('DELAY', delayAndThenPush); | |
}; | |
const sagaMiddleware = createSagaMiddleware(); | |
const store = createStore(reducer, initialState, applyMiddleware(sagaMiddleware)); | |
sagaMiddleware.run(mySaga); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment