Redux 的适用场景:多交互、多数据源。
Redux用一个单独的常量状态树(对象)保存这一整个应用的状态,这个对象不能直接被改变。当一些数据变化了,一个新的对象就会被创建(使用actions和reducers)。
redux 是一个范用的状态管理框架
主要是解决了组件间状态共享的问题
原理是集中式管理
redux中有三个基本概念,Action,Reducer,Store。
store 仓库
维持应用的 state;
提供 getState() 方法获取 state;
提供 dispatch(action) 方法更新 state;
通过 subscribe(listener) 注册监听器。
action 中发送过来的对象 必须有一个type属性
reducer 他是一个纯函数 他会跟action发送过来的type类型做逻辑上的处理(使用switch方法进行判断)
安装 npm install redux -D
引入必要组件:
import { createStore} from 'redux';
生成store:
const store = createStore(reducer, state初始状态[可选]);
取得当前时刻的state:
const state = store.getState();
发出action
store.dispatch({
type: 'ADD_TODO',
text: 'Learn Redux'
});
设置监听函数:
store.subscribe(callback);
Reducer 函数最重要的特征是,它是一个纯函数。也就是说,只要是同样的输入,必定得到同样的输出。
约束:
不得改写参数
不能调用系统 I/O 的API
不能调用Date.now()或者Math.random()等不纯的方法,因为每次会得到不一样的结果
Reducer 函数里面不能改变 State,必须返回一个全新的对象,请参考下面的写法。
// State 是一个对象
function reducer(state, action) {
return Object.assign({}, state, { thingToChange });
// 或者
return { ...state, ...newState };
}
// State 是一个数组
function reducer(state, action) {
return [...state, newItem];
}