redux 最简例子

方便初学redux的同学学习,这里是最简单的redux例子

 1 import React, {Component, PropTypes} from 'react'
 2 import ReactDOM from 'react-dom'
 3 import {createStore} from 'redux'
 4 import {Provider, connect} from 'react-redux'
 5 
 6 // React组件
 7 class Counter extends Component {
 8     render() {
 9         const {value, onIncreaseClick} = this.props
10         return (
11             <div>
12                 <span>{value}</span>
13                 <button onClick = {onIncreaseClick}> Increase </button></div>
14         )
15     }
16 }
17 
18 // Props
19 Counter.propTypes = {
20     value: PropTypes.number.isRequired,
21     onIncreaseClick: PropTypes.func.isRequired
22 }
23 
24 // Action
25 const increaseAction = {
26     type: 'increase'
27 }
28 
29 // Reducer
30 function counter(state = {
31     count: 0
32 }, action) {
33     let count = state.count
34     switch (action.type) {
35         case 'increase':
36             return {
37                 count: count + 1
38             }
39         default:
40             return state
41     }
42 }
43 
44 // Store
45 let store = createStore(counter)
46 
47 // 把state转换成props,在组件中接收使用
48 function mapStateToProps(state) {
49     return {
50         value: state.count
51     }
52 }
53 
54 // 把action对应的方法转换成props,在组件中接收使用
55 function mapDispatchToProps(dispatch) {
56     return {
57         onIncreaseClick: () => dispatch(increaseAction)
58     }
59 }
60 
61 // connected Component
62 let App = connect(
63     mapStateToProps,
64     mapDispatchToProps
65 )(Counter)
66 
67 ReactDOM.render(
68     <Provider store={store}>
69         <App />
70     </Provider>,
71     document.getElementById('root')
72 )
 

 

posted @ 2018-04-12 15:47  herorest  阅读(185)  评论(0编辑  收藏  举报