Rails-style: separate folders for “actions”, “constants”, “reducers”, “containers”, and “components”
Domain-style: separate folders per feature or domain, possibly with sub-folders per file type
“Ducks”: similar to domain style, but explicitly tying together actions and reducers, often by defining them in the same file
npm install redux react-redux --save-dev
import { createStore , combineReducers } from 'redux' ;
import { Provider } from 'react-redux' ;
const store = createStore (
combineReducers ( {
something : ( state , action ) => { } ,
} ) ,
) ;
< Provider store = { store } >
< MyRootComponent / >
< / Provider >
Actions, Action creators and Reducers
const ADD_SOME = 'ADD_SOME' ;
const RM_SOME = 'RM_SOME' ;
function addSomething ( payload ) {
return {
type : ADD_SOME ,
payload,
} ;
}
function removeSomething ( payload ) {
return {
type : RM_SOME ,
payload,
} ;
}
function somethingReducer ( state = [ ] , action ) {
if ( action . type === ADD_SOME ) {
return state . concat ( [ action . payload ] ) ;
}
if ( action . type === RM_SOME ) {
return state . filter ( x => x . id !== action . payload . id ) ;
}
return state ;
}
import { bindActionCreators } from 'redux' ;
const MyComponent = ( { something, addSomething, removeSomething } ) => {
return (
< div >
< div > Count: { something . length } < / div >
< button onClick = { ( ) => addSomething ( { } ) } > Add< / button >
< button onClick = { ( ) => removeSomething ( { } ) } > Remove< / button >
< / div >
) ;
} ;
function mapStateToProps ( state ) {
return {
something : state . something ,
} ;
}
function mapDispatchToProps ( dispatch ) {
return bindActionCreators ( { addSomething, removeSomething } , dispatch ) ;
}
export default connect (
mapStateToProps ,
mapDispatchToProps ,
) ( MyComponent ) ;
npm install --save redux-thunk
import { createStore , applyMiddleware } from 'redux' ;
import thunk from 'redux-thunk' ;
import rootReducer from './reducers' ;
const store = createStore ( rootReducer , applyMiddleware ( thunk ) ) ;