个人笔记, 基于官方英文教程, 添加了一些批注, 有一些单词翻译起来真困难
Redux 基于严格单向数据流实现 反正就是为了打破 React 自身的数据流而创建的
store.dispatch(action)
action 的格式如下:
{ type: 'LIKE_ARTICLE', articleId: 42 }
{ type: 'FETCH_USER_SUCCESS', response: { id: 3, name: 'Mary' } }
{ type: 'ADD_TODO', text: 'Read the Redux docs.' }
通过这个
action
对于用户操作的描述可以变得非常的具象
默认会提交两个参数给 Reducer:
dispatcher
的参数action
参考下文提到的
combineReducers()
的使用示例
现在这个时候已经获取到了下一个状态了
如果我使用store.subscribe(listener)
注册了个监听器,会在这个时候被调用,并且可以通过store.getState()
获取到当前的状态
最后通过更新之后的状态刷新 UI
pure function: 可以根据传入的值预测结果,并且不会影响其他值, 即不改变传入的值也不会创建闭包
基本格式:
(previousState, action) => newState
必须满足以下几点:
Date.now()
或者 Math.random()
(这些函数的结果无法预料)一个详细一点的例子:
export default (state = 0, action) => {
switch (action.type) {
case 'INCREMENT':
return state + 1
case 'DECREMENT':
return state - 1
default:
return state
}
}
action
的类型进行不同的处理action
不一定要字符串,可以传更多类型,甚至可以传一个 obj 进来可以通过combineReducers
函数返回多个 sub-Reducer, 例如上面返回了a
和b
两个 reducer
import { combineReducers } from 'redux'
const a = (state = 0, action) => {
switch (action.type) {
case 'INCREMENT':
return state + 1
default:
return state
}
}
const b = (state = 0, action) => {
switch (action.type) {
case 'INCREMENT':
return state + 2
default:
return state
}
}
const e = combineReducers({
a,
b
})
export default e
如果我们在 reducer 里面提供了多个函数 那么当我们分发一个特定动作的时候, 比如
console.log( store.dispatch({type: 'INCREMENT'}) )
这个动作就会提交到所有的函数之上, 也就是说, 上方a
会接收这个动作,b
也会接受这个动作,然后以下面的格式进行返回:
{
a: 1, //经过 a 处理之后的状态
b: 2 //经过 b 处理之后的状态
}
类似于用参数{state, action}便利并执行了整个 reducer 里面所有 reducer 函数
用于分发 Action 到 Reducers, 他需要做这样的操作
getState()
获取到状态dispatch(action)
来分发动作subscribe(listener)
来注册监听器subscribe(listener)
的返回值决定是否接触监听器创建 Store 的例子:
import { createStore } from 'redux'
import todoApp from './reducers'
const store = createStore(todoApp)