Ducks-modular-redux方法,将{actionTypes,actions,reducer}
放于一个文件中,规则
MUST export default a function called reducer()
MUST export its action creators as functions
MUST have action types in the form npm-module-or-app/reducer/ACTION_TYPE
MAY export its action types as UPPER_SNAKE_CASE, if an external reducer needs to listen for them, or if it is a published reusable library
modules/counter.js
const INCREMENT = 'app/counter/INCREMENT'
export default function reducer(state=0,action){
switch(action.type){
case INCREMENT:
return state + 1;
default:
return state;
}
}
export function increment(){
return {
type:INCREMENT
}
}
compoments/Counter.js
import React,{PropTypes, Component} from 'react'
export default class Counter extends Component{
static propTypes = {
counter:PropTypes.number.isRequired,
increment:PropTypes.func.isRequired
};
constructor(props){
super(props)
}
render(){
const {counter, increment} = this.props;
return(
<div>{counter}<button onClick={increment}>+</button></div>
)
}
}
containers/Counter.js
import {bindActionCreators} from 'redux'
import {connect} from 'react-redux'
import Counter from '../components/Counter'
import * as CounterActions from '../modules/counter'
const mapStateToProps = state => ({counter:state.counter})
const mapDispatchToProps = dispatch => bindActionCreators(CounterActions,dispatch)
export default connect(mapStateToProps,mapDispatchToProps)(Counter)
modules/reducers.js
import {combineReducers} from 'redux'
import counter from './counter'
const rootReducer = combineReducers({
counter
})
export default rootReducer
参考:
redux中文文档