一、关于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'; // 创建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
转码