redux
1、Redux简介
在Redux中,最为核心的概念就是 state、action 、reducer 以及 store。
1、action:动作
function addItem(text) { return { type: types.ADD_ITEM, text } }
2、state:
状态
3、reducer
Reducer 是一个普通的回调函数。
当它被Redux调用的时候会为他传递两个参数State 和 Action。
Reducer会根据 Action 的type来对旧的 State 进行操作。返回新的State。
看起来是下面这样的:
/**
* 添加
*
* @param {String} 添加的文字
*
* @return {Object} 将要添加的数据
*/
let createItem = text => {
let time = Date.now();
return {
id: Math.random().toString(36).split('.').join(''),
addTime: time,
updateTime: time,
status: false,
text
}
}
/**
* Reducer
*
* @param State
* @param Action
*
* @return new State
*/
let reducer = (state = [], action) => {
switch (action.type) {
case ADD_ITEM:
return [createItem(action.text), ...state]
default:
return state
}
}
store:
提供方法去操作数据, 一个应用只有一个Store
let store = createStore(rootReducers, initialState)
store有四个方法。
- getState: 获取应用当前State。
- subscribe:添加一个变化监听器。
- dispatch:分发 action。修改State。
- replaceReducer:替换 store 当前用来处理 state 的 reducer。
简单的说,Redux所想表达的就是这些内容,所以它的学习曲线不会很陡。对于程序员来讲,阅读代码会比阅读文字舒服,那么我们如何简单地用redux实现
浙公网安备 33010602011771号