Flux的核心思想就是数据和逻辑永远是单向流动的
1、安装
npm install redux --save2、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()获取statedispatch(action)更新statesubscribe(listener)注册监听器5、关于redux模块中常用的方法
1、createStore利用纯函数创建出一个store2、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转码