关于redux的认识

一、关于Flux的认识

Flux的核心思想就是数据逻辑永远是单向流动的

这里写图片描述

二、redux的认识

  • 1、安装

    npm install redux --save
  • 2、Action实质上就是一个对象,一个带typekey的对象

    export const ADD_TODO = 'ADD_TODO';
    export const addTodo = (text) => ({
        type: ADD_TODO,
        text
    })
  • 3、Dispatherredux中是一个纯函数,接收一个stateaction返回一个新的state

    export const todos = (state = 0,action) =>{
        switch(action.type){
            case:'xxx1':
                return state + 1;
            case:'xxx2':
                return state - 1;
            default:
                return state;
        }
    }
    • 上面的state可以是基础数据类型、对象、数组

    上面方式有点错误,直接修改了state,如果state是一个对象,对象是引用数据类型,当state改变的时候,前后两个state将会指向同一个地址,在react-redux就会判断是相同的state就不会重新渲染

  • 4、storeredux中直接提供了一个方法来创建,主要职能就是将actionreducer连接在一起

    import {createStore} from 'redux';
    let store = createStore(我们自己创建的那个纯函数);

    store提供的主要方法

    • getStore()获取state
    • dispatch(action)更新state
    • subscribe(listener)注册监听器
  • 5、关于redux模块中常用的方法

    • 1、createStore利用纯函数创建出一个store
    • 2、combineReducers将零散的reducer整合到一起,一起导出

      const todoApp = combineReducers({
          todos,
          visibilityFilter
      })

三、代码

  • 1、全部的代码

    import {createStore} from 'redux';
    
    // 定义几个常量(一般项目开发中定义常量)
    const INCREMENT = 'INCREMENT';
    const DECREMENT = 'DECREMENT';
    const INCRETWO = 'INCRETWO';
    // 创建action
    const action1 = () => ({
        type: INCREMENT,
    });
    const action2 = () => ({
        type: DECREMENT,
    })
    const action3 = () => ({
        type:INCRETWO
    })
    // 创建一个reducer函数
    const count = (state = 0, action) => {
        switch (action.type) {
            case INCREMENT:
                return state + 1;
            case DECREMENT:
                return state - 1;
            case INCRETWO:
                return state + 2;
            default:
                return state;
        }
    }
    // 创建一个store
    let store = createStore(count);
    
    // 利用store的方法来获取与发送一个值
    let currentValue = store.getState();
    // 监听state的变化
    store.subscribe(() => {
        let previousValue = currentValue;
        currentValue = store.getState();
        console.log(`当前值:${currentValue}上一个值:${previousValue}`);
    });
    
    // 事件派发
    store.dispatch(action1());
    store.dispatch(action1());
    store.dispatch(action1());
    store.dispatch(action2());
    store.dispatch(action3());
  • 2、代码说明

    上面的代码直接跑会报错,必须依赖ES6转码

四、代码见demo

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

水痕01

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值