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


    先上代码

     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             <div>
    12                 <button onClick={minus}>-</button>
    13                 <p>{count}</p>
    14                 <button onClick={plus}>+</button>
    15             </div>
    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     <Provider store={store}>
    74         <App />
    75     </Provider>,
    76     document.getElementById('root')
    77 )

     数据变动的流程

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

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

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

    store对应着reducer

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

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

  • 相关阅读:
    简单理解Socket
    TCP/IP、Http、Socket的区别
    iOS,一行代码进行RSA、DES 、AES、MD5加密、解密
    iOS开发
    我的问题
    Windows 摄像头数据
    学习记录
    编码转换
    QString 编码转换
    参考网页
  • 原文地址:https://www.cnblogs.com/xiedashuaige/p/8228222.html
Copyright © 2020-2023  润新知