一个超级简单的demo带你走进redux的大坑

综合技术 2018-01-07

先上代码

 1 import React, { Component } from 'react';
 2 import ReactDOM from 'react-dom';
 3 import { createStore } from 'redux';
 4 import { Provider, connect } from 'react-redux';
 5 
 6 
 7 class App extends Component{
 8     render(){
 9         const {count, plus, minus} = this.props;
10         return (
11             
12 13

{count}

14 15
16 ) 17 } 18 } 19 20 21 22 //action 23 const plusAcion = { 24 type: 'PLUS', 25 count: 10 26 } 27 28 const minusAction = { 29 type: 'MINUS', 30 count: 20 31 } 32 33 //reducer 34 const initialState = { 35 count: 0 36 } 37 const reducer = (state = initialState, action) => { 38 switch (action.type) { 39 case 'PLUS' : 40 return { 41 count: state.count + action.count 42 } 43 case 'MINUS' : 44 return { 45 count: state.count - action.count 46 } 47 default: 48 return initialState; 49 } 50 } 51 52 //store 53 let store = createStore(reducer) 54 55 //映射Redux state到组件的属性 56 function mapStateToProps(state) { 57 return { count: state.count } 58 } 59 60 //映射Redux actions到组件的属性 61 function mapDispatchToProps(dispatch){ 62 return{ 63 plus:()=>dispatch(plusAcion), 64 minus:()=>dispatch(minusAction) 65 } 66 } 67 68 //连接组件 69 App = connect(mapStateToProps, mapDispatchToProps)(App) 70 71 //渲染组件 72 ReactDOM.render( 73 74 75 , 76 document.getElementById('root') 77 )

数据变动的流程

用户在界面上点击加号或者减号

通过点击的那个函数在mapDispatchToProps映射上找到对于的action

然后action就去找组件绑定的store

store对应着reducer

reducer执行当前type对应的那个switch,更改state上面的数据

数据通过mapStateToProps映射到了组件上

博客园-原创精华区

责编内容by:博客园-原创精华区 (源链)。感谢您的支持!

您可能感兴趣的

Cedux: Experimenting with the Redux Model in C The world of embedded software development can feel like a very isolated place. Earlier in my career...
Making HOC with prop type inference from Recompose... It seems like the type annotation for react-redux’s connect is not compatible with the recompose...
Build faster with React and Redux by generating co... hygen is the simple, fast, and scalable code generator that lives in your project. Qui...
React+Redux仿Web追书神器 引言 由于现在做的react-native项目没有使用到redux等框架,写了一段时间想深入学习react,有个想法想做个demo练手下。由于正好在学习开源的Android小说阅读器-- 任阅 ...
Testing Redux: Async Action Creators One of the biggest (and often overlooked) advantages of Redux apps is how inherently testable they a...