Last active
November 30, 2017 19:04
-
-
Save dkarmalita/5336cc50568fc884082f06ef04a1ba5b to your computer and use it in GitHub Desktop.
Example: React + Redux
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
import React, { Component, PropTypes } from 'react'; | |
import { render } from 'react-dom'; | |
import { createStore, combineReducers, bindActionCreators } from 'redux' | |
import { Provider, connect } from 'react-redux' | |
// ## Simple component | |
// =================== | |
class Root extends Component { | |
constructor(props) { | |
super(props); | |
} | |
render() { | |
return <div> | |
<div>{this.props.text}</div> | |
<input type="button" value="Click Me" onClick={()=>this.props.doAction('Hi There!')}/> | |
</div> | |
} | |
} | |
// ## Reducer & store | |
// ================== | |
// ### First reducer | |
const userInitialState = { | |
user: 'Unknown User' | |
}; | |
function userReducer(state = userInitialState) { | |
return state; | |
} | |
// ### Simple store | |
//const store = createStore( textReducer, textInitialState) | |
//function mapStateToProps (state) { | |
// return { | |
// user: state.user, | |
// text: state.text | |
// } | |
//} | |
// ### Second reducer | |
// #### Action | |
function setTextAction(payload) { | |
return { | |
type: 'SET_TEXT', | |
// payload: "Hi there!" | |
payload | |
} | |
} | |
const textInitialState = { | |
text: 'Hello World' | |
}; | |
function textReducer(state = textInitialState, action) { | |
switch (action.type) { | |
case 'SET_TEXT': | |
return { ...state, text: action.payload } | |
default: | |
return state; | |
} | |
} | |
// ### Combined reducer | |
const rootReducer = combineReducers({ | |
textReducer, | |
userReducer | |
}) | |
const store = createStore(rootReducer) | |
// ## Connected component and mapping props | |
// ======================================== | |
// ### Mapping the props | |
function mapStateToProps (state) { | |
// console.log(state) | |
return { | |
// user: state.user, | |
// text: state.text | |
text: state.textReducer.text, | |
user: state.userReducer.user | |
} | |
} | |
function mapDispatchToProps(dispatch) { | |
return { | |
doAction: bindActionCreators(setTextAction, dispatch) | |
} | |
} | |
const ConnectedRoot = connect(mapStateToProps, mapDispatchToProps)(Root) | |
ConnectedRoot.propTypes = { | |
text: PropTypes.string,//.isRequired, | |
user: PropTypes.string | |
} | |
render( | |
<Provider store={store}> | |
<ConnectedRoot/> | |
</Provider>, | |
document.getElementById('root') | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment