React-Redux-Counter

by Allie Yu

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.0.5/redux.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-redux/7.2.0/react-redux.min.js"></script>
<div id="root"></div>

Babel + JSX

// actions
const increment = number => ({
	type: INCREMENT,
})

const decrement = number => ({
	type: DECREMENT,
})

// reducer
const INITIAL_STATE = {
  count:0
}
const counterReducer = (state = INITIAL_STATE , action) => {
  switch(action.type) {
    case 'INCREMENT':
      return Object.assign({}, state, { count: state.count + 1});
    case 'DECREMENT':
      return Object.assign({}, state, { count: state.count - 1});
   	default:
    	return state;
  }
};

/* const Reducers = combineReducers({
    counterReducer, 
}) */


class App extends React.Component {
  constructor(props) {
    super(props)
    
  }
  
  increment = () => {
    this.props.Increase()
  }
  
  decrement = () => {
    this.props.Decrease()
  }
  
  render(){
  	const {count} = this.props
    return (
      <div>
          <div>{this.props.count}</div>
          <button onClick={this.increment}> + </button>
          <button onClick={this.decrement}> - </button>
      </div>
    )
  }
}

const Provider = ReactRedux.Provider;
// store
let store = Redux.createStore(counterReducer);

//建立一个从(外部的)state对象到(展示型组件的)props对象的映射关系
//counter与展示型组件同名
const mapStateToProps = state => {
  return {count:state.count}
};

//建立展现型组件的参数到store.dispatch方法的映射
//传递this.props方法,执行counterAddAction(计数器增加Action)对应的函数
const mapDispatchToProps = dispatch => {
  return {
    Increase: () => {
      dispatch({type: "INCREMENT"})
    },
    Decrease: () => {
      dispatch({type: "DECREMENT"})
    }
  }
};

const CounterApp = ReactRedux.connect(mapStateToProps, mapDispatchToProps)(App);


ReactDOM.render(
	<Provider store={store}>
	    <CounterApp />
	</Provider>,
  document.getElementById('root')
);

//index.js listen
//store.subscribe(render)