美文网首页
React Redux Template

React Redux Template

作者: Moon_Yue | 来源:发表于2016-02-27 21:31 被阅读186次

    Ducks-modular-redux方法,将{actionTypes,actions,reducer}放于一个文件中,规则

    1. MUST export default a function called reducer()
      
    2. MUST export its action creators as functions
      
    3. MUST have action types in the form npm-module-or-app/reducer/ACTION_TYPE
      
    4. 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中文文档

    相关文章

      网友评论

          本文标题:React Redux Template

          本文链接:https://www.haomeiwen.com/subject/rkgwkttx.html