关于redux的认识
来源:互联网 发布:大数据的主要来源于 编辑:程序博客网 时间:2024/06/02 04:22
一、关于Flux
的认识
Flux
的核心思想就是数据和逻辑永远是单向流动的
二、redux
的认识
1、安装
npm install redux --save
2、
Action
实质上就是一个对象,一个带type
的key
的对象export const ADD_TODO = 'ADD_TODO';export const addTodo = (text) => ({ type: ADD_TODO, text})
3、
Dispather
在redux
中是一个纯函数,接收一个state
和action
返回一个新的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、
store
在redux
中直接提供了一个方法来创建,主要职能就是将action
和reducer
连接在一起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、
三、代码
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
阅读全文
0 0
- 关于redux的认识
- redux的认识
- redux中间件的认识
- 认识redux的store,reducer,action
- react项目学习笔记四(redux和redux的中间件redux-thunk的认识)
- 关于redux的入门简介
- 关于redux
- 对redux的认识(源码深度解读)
- 关于Flux,Vuex,Redux的思考
- 关于react-redux的一些看法
- 关于redux+react的一些思考
- 关于场景的认识
- 关于朝令夕改的认识
- 关于委托的认识
- 关于LinQ的认识
- 关于dojo的认识
- 关于DDD的认识
- 关于粒度的认识
- Spring MVC中ajax的处理
- refresh的停车场
- 小白学tkinter(pack()包管理器grid()网格管理器place()位置管理器)
- 元素位置互换之移位算法
- Javascript Array forEach()中无法return和break,代替方法some()与every()
- 关于redux的认识
- php5.6.32版本编译安装参数官方说明参考
- 118. Pascal's Triangle
- 切水王#7
- MySQL与SQLite的区别及迁移
- 2017.08.05【NOIP提高组】模拟赛B组小结
- 数组---二分查找
- 关于复选框全选,全不选以及使用按钮传值
- bzoj1668 [Usaco2006 Oct]Cow Pie Treasures 馅饼里的财富(dp)