React + redux basics
actions/index.js
export function actionFunction() {
/*do somethings with data*/
return {
type: 'SAMPLE_ACTION' /*action type name, best from constants folder*/
payload: data /*your data*/
}
}
reducers/reducer_name.js
export default function(state = /*initial state*/ null, action) {
switch(action.type) {
/* use action names from costants */
case 'SAMPLE_ACTION': {
/* always return piece of app redux state */
/* never modify app state or any of its pieces */
return action.payload
}
}
}
Always use combineReducers from redux in reducers/index.js
const rootReducer = combineReducers({
reducer_name: ReducerName
});
export default rootReducer;
In your main js file /index.js
import your combined reducers and use createStore method from redux
const createStoreWithMiddleware = applyMiddleware()(createStore)
/*...*/
<Provider store={createStoreWithMiddleware(reducers)}>
<App />
</Provider>
In your container, where you want to use that action use functions: mapStateToProps
and mapDispatchToProps
and
/* you can use React.Component class as base or do functional component */
const ContainerName = (props) => {
return (
/*
use some jsx magic here, eg.
<img src={props.photo.image.source} onClick={() => props.doMagic()}/>
*/
)
}
function mapStateToProps(state) {
return { photo: state.photo }
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({ doMagic: doMagic }, dispatch)
}
export default connect(mapStateToProps, mapDispatchToProps)(ContainerName)