什么是redux
Redux对于JavaScript应用而言是一个可预测状态的容器。换言之,它是一个应用数据流框架,而不是传统的像underscore.js或者AngularJs那样的库或者框架。
Redux最主要是用作应用状态的管理。简言之,Redux用一个单独的常量状态树(对象)保存这一整个应用的状态,这个对象不能直接被改变。当一些数据变化了,一个新的对象就会被创建(使用actions和reducers)。
redux 是一个范用的状态管理框架
主要是解决了组件间状态共享的问题
原理是集中式管理
Redux 的适用场景:多交互、多数据源。
(1)基本概念
redux中有三个基本概念,Action,Reducer,Store。
1.Store
store是redux库中的createStore方法,生成的一个对象,这个对象中,存储的就是我们的公有数据。
import { createStore } from 'redux';
const Store = createStore(fn);
store 仓库
维持应用的 state;
提供 getState() 方法获取 state;
提供 dispatch(action) 方法更新 state;
通过 subscribe(listener) 注册监听器。
- Action
redux认为,一个state对应着一个view,state改变,view跟着改变。对于用户而言,接触到的可能就只有view,所以redux需要提供一种用户通过view,来更改state,从而让view发生变化的东西。而这个东西就是Action。
var Action = {
type: 'ADD',
text: 'value'
}
export default Action;
action用来描述的是用户行为,它是一个对象,redux通过dispatch这个action来更改state。
action 中发送过来的对象 必须有一个type属性
- Reducer
reducer 他是一个纯函数 他会跟action发送过来的type类型做逻辑上的处理(使用switch方法进行判断)
// State 是一个对象
function reducer(state, action) {
return Object.assign({}, state, { thingToChange });
// 或者
return { ...state, ...newState };
}
// State 是一个数组
function reducer(state, action) {
return [...state, newItem];
}
Reducer 函数最重要的特征是,它是一个纯函数。也就是说,只要是同样的输入,必定得到同样的输出。
约束:
不得改写参数
不能调用系统 I/O 的API
不能调用Date.now()或者Math.random()等不纯的方法,因为每次会得到不一样的结果
(2)redux的流程
View调用store.dispatch发起Action->store接受Action(action传入reducer函数,reducer函数返回一个新的state)->通知store.subscribe订阅的重新渲染函数
redux的优缺点
优:redux把流程规范了,统一渲染根节点虽然对代码管理上规范了一些,只要有需要显示数据的组件,当相关数据更新时都会自动进行更新。
减少手动编码量,提高编码效率。
缺:一个组件所需要的数据,当相关数据更新时,组件要重新render,可能会有效率影响,或者需要写复杂的shouldComponentUpdate进行判断
Redux核心API
安装 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 函数里面不能改变 State,必须返回一个全新的对象,请参考下面的写法。
// State 是一个对象
function reducer(state, action) {
return Object.assign({}, state, { thingToChange });
// 或者
return { ...state, ...newState };
}
// State 是一个数组
function reducer(state, action) {
return [...state, newItem];
}
Reducer拆分
import {combineReducers} from 'redux';
Const reducer=combineReducers({
Xxx:xxx(函数-业务逻辑)
})