Redux 是 JavaScript 状态容器,提供可预测化的状态管理。可以让你构建一致化的应用,运行于不同的环境(客户端、服务器、原生应用),并且易于测试。Redux 除了和 React 一起用外,还支持其它界面库。 它体小精悍(只有2kB,包括依赖)。
http://www.redux.org.cn/ 中文网址 http://redux.js.org/ 英文网址
npm install --save redux
安装
import { createStore } from 'redux';
引入
单一数据源、state是只读的,使用纯函数来执行修改
当安装好redux包并引入以后,我们通过creteStore(reducer)创建一个store状态机,用于状态管理。reducer是一个纯函数【纯函数即返回值只有传入的参数决定】,reducer(state,action)有2个参数,state为当前的状态,action 就是一个描述“发生了什么”的普通对象,reducer中通过switch流程控制语句判断action.type的值,来更改state。通过使用store.dispatch(action)来触发aciton的改变,然后通过store.subscribe(()=>{}),来手动订阅更新,当store.dispatch(action)后,就会触发store.subscribe。通过使用store.getState()获取当前store中state状态
import{ render } from 'react-dom';
import { createStore } from 'redux';
/**
* 这是一个 reducer,形式为 (state, action) => state 的纯函数。
* 描述了 action 如何把 state 转变成下一个 state。
*
* state 的形式取决于你,可以是基本类型、数组、对象、
* 甚至是 Immutable.js 生成的数据结构。惟一的要点是
* 当 state 变化时需要返回全新的对象,而不是修改传入的参数。
*
* 下面例子使用 `switch` 语句和字符串来做判断,但你可以写帮助类(helper)
* 根据不同的约定(如方法映射)来判断,只要适用你的项目即可。
*/
function counter(state = 0, action) {
switch (action.type) {
case 'INCREMENT':
return state + 1;
case 'DECREMENT':
return state - 1;
default:
return state;
}
}
// 创建 Redux store 来存放应用的状态。
// API 是 { subscribe, dispatch, getState }。
let store = createStore(counter);
// 可以手动订阅更新,也可以事件绑定到视图层。
store.subscribe(() =>
console.log(store.getState())
);
// 改变内部 state 惟一方法是 dispatch 一个 action。
// action 可以被序列化,用日记记录和储存下来,后期还可以以回放的方式执行
store.dispatch({ type: 'INCREMENT' });
// 1
store.dispatch({ type: 'INCREMENT' });
// 2
store.dispatch({ type: 'DECREMENT' });
// 1
render(
//这里我们通过将store传入组件,后续我们即可以通过this.props.store来调用store
<Counter store={store} />,
document.querySelector('#root')
)
const add = (num = 1) => {
return {
type: 'ADD',
num
}
}
const reduce = (num = 1) => {
return {
type: 'REDUCE',
num
}
}
store.dispatch(add(5))
store.dispatch(reduce(2))
在处理action:type时,如果type值我们写错了,redux也不会报错,他会执行default默认值,这时我们就很尴尬了,所以我们常用的办法时,在action文件夹里创建一个actionType文件,将所有action里要用到的type值,用变量存起来,变量值为字符串即下面的做法,后面我们将type类型用变量引入,加入不存在这个变量的话,就会出现undefined报错
// 定义action的类型
export const ADD = 'ADD';
export const REDUCE = 'REDUCE';
export const START_GET_DATA = 'START_GET_DATA';
export const GET_DATA_SUCCESS = 'GET_DATA_SUCCESS';
// 导入actionType
import {
ADD,
REDUCE,
START_GET_DATA,
GET_DATA_SUCCESS
} from './actionType';
// ·加· 这个动作的action creator,
export const add = (num = 1) => {
return {
type: ADD,
num
}
}
reducers
import {
combineReducers
} from 'redux';
import cart from './cart';
// combineReducers 是redux提供的一个方法,用于合并多个reducer
export default combineReducers({
cart
})
combineReducers使用示例