关于redux的认识

来源:互联网 发布:大数据的主要来源于 编辑:程序博客网 时间:2024/06/02 04:22

一、关于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';// 创建actionconst 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;    }}// 创建一个storelet 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

原创粉丝点击