一、設計思想
① Web 應用是一個狀態機,視圖與狀態是一一對應的。
② 所有的狀態,保存在一個對象裏面。
二、基本概念和 API
1、Store
Store 是保存數據的地方,可以把它看成一個容器。整個應用只能有一個 Store。
Redux 提供 createStore
這個函數來生成 Store:
import { createStore } from 'redux'
const store = createStore(fn)
上面代碼中,createStore
函數接受另一個函數作爲參數,返回新生成的 Store 對象。
2、State
Store 對象包含所有數據,如果想得到某個時點的數據,可以通過 store.getState()
拿到,這裏的 State 就是該時點 Store 的數據集合。
import { createStore } from 'redux'
const store = createStore(fn)
const state = store.getState()
3、Action
State 的變化,會導致 View 的變化。但用戶接觸不到 State,只能接觸到 View。所以,State 的變化必須是 View 導致的。Action 就是 View 發出的通知,表示 State 應該要發生變化了。
Action 是一個對象。其中的 type
屬性是必須的,表示 Action 的名稱。其他屬性可以自由設置,社區有一個規範可以參考。
const action = {
type: 'ADD_TODO',
payload: 'Learn Redux'
}
上面代碼中,Action 的名稱是 ADD_TODO
,它攜帶的信息是字符串 Learn Redux
。
可以這樣理解,Action 描述當前發生的事情。改變 State 的唯一辦法,就是使用 Action。它會運送數據到 Store。
4、Action Creator
View 要發送多少種消息,就會有多少種 Action。如果都手寫,會很麻煩。可以定義一個函數來生成 Action,這個函數就叫 Action Creator。
const ADD_TODO = '添加 TODO'
function addTodo(text) {
return {
type: ADD_TODO,
text
}
}
const action = addTodo('Learn Redux')
上面代碼中,addTodo
函數就是一個 Action Creator。
5、store.dispatch()
store.dispatch()
是 View 發出 Action 的唯一方法。
import { createStore } from 'redux'
const store = createStore(fn)
store.dispatch({
type: 'ADD_TODO',
payload: 'Learn Redux'
})
上面代碼中,store.dispatch
接受一個 Action 對象作爲參數,將它發送出去。
結合 Action Creator,這段代碼可以改寫如下。
store.dispatch(addTodo('Learn Redux'))
6、Reducer
Store 收到 Action 以後,必須給出一個新的 State,這樣 View 纔會發生變化。這種 State 的計算過程就叫做 Reducer。
Reducer 是一個函數,它接受 Action 和當前 State 作爲參數,返回一個新的 State。
const reducer = function (state, action) {
// ...
return new_state
}
整個應用的初始狀態,可以作爲 State 的默認值。下面是一個實際的例子。
const defaultState = 0
const reducer = (state = defaultState, action) => {
switch (action.type) {
case 'ADD':
return state + action.payload
default:
return state
}
}
const state = reducer(1, {
type: 'ADD',
payload: 2
})
上面代碼中,reducer
函數收到名爲 ADD
的 Action 以後,就返回一個新的 State,作爲加法的計算結果。其他運算的邏輯(比如減法),也可以根據 Action 的不同來實現。
實際應用中,Reducer 函數不用像上面這樣手動調用,store.dispatch
方法會觸發 Reducer 的自動執行。爲此,Store 需要知道 Reducer 函數,做法就是在生成 Store 的時候,將 Reducer 傳入 createStore
方法。
import { createStore } from 'redux'
const store = createStore(reducer)
上面代碼中,createStore
接受 Reducer 作爲參數,生成一個新的 Store。以後每當 store.dispatch
發送過來一個新的 Action,就會自動調用 Reducer,得到新的 State。
7、純函數
Reducer 函數最重要的特徵是,它是一個純函數。也就是說,只要是同樣的輸入,必定得到同樣的輸出。
純函數是函數式編程的概念,必須遵守以下一些約束:
- 不得改寫參數
- 不能調用系統 I/O 的 API
- 不能調用 Date.now() 或者 Math.random() 等不純的方法,因爲每次會得到不一樣的結果
由於 Reducer 是純函數,就可以保證同樣的 State,必定得到同樣的 View。但也正因爲這一點,Reducer 函數裏面不能改變 State,必須返回一個全新的對象,參考下面寫法:
// State 是一個對象
function reducer(state, action) {
return Object.assign({}, state, { thingToChange })
// 或者
return { ...state, ...newState }
}
// State 是一個數組
function reducer(state, action) {
return [...state, newItem]
}
最好把 State 對象設成只讀,無法改變,要得到新的 State,唯一辦法就是生成一個新對象。這樣的好處是,任何時候,與某個 View 對應的 State 總是一個不變的對象。
8、store.subscribe()
Store 允許使用 store.subscribe
方法設置監聽函數,一旦 State 發生變化,就自動執行這個函數。
import { createStore } from 'redux'
const store = createStore(reducer)
store.subscribe(listener)
顯然,只要把 View 的更新函數(對於 React 項目,就是組件的 render
方法或 setState
方法)放入 listen
,就會實現 View 的自動渲染。
store.subscribe
方法返回一個函數,調用這個函數就可以解除監聽。
let unsubscribe = store.subscribe(() =>
console.log(store.getState())
)
unsubscribe()
三、Store 的實現
上一節總結了 Store 提供的三個方法:
- store.getState()
- store.dispatch()
- store.subscribe()
import { createStore } from 'redux'
let { subscribe, dispatch, getState } = createStore(reducer)
createStore
方法還可以接受第二個參數,表示 State 的最初狀態。這通常是服務器給出的。
let store = createStore(todoApp, window.STATE_FROM_SERVER)
上面代碼中,window.STATE_FROM_SERVER
就是整個應用的狀態初始值。注意,如果提供了這個參數,它會覆蓋 Reducer 函數的默認初始值。
下面是 createStore
方法的一個簡單實現,可以瞭解一下 Store 是怎麼生成的:
const createStore = (reducer) => {
let state
let listeners = []
const getState = () => state
const dispatch = (action) => {
state = reducer(state, action)
listeners.forEach((listener) => listener())
}
const subscribe = (listener) => {
listeners.push(listener)
return () => {
listeners = listeners.filter((l) => l !== listener)
}
}
dispatch({})
return { getState, dispatch, subscribe }
}
四、Reducer 的拆分
Reducer 函數負責生成 State。由於整個應用只有一個 State 對象,包含所有數據,對於大型應用來說,這個 State 必然十分龐大,導致 Reducer 函數也十分龐大。
舉個例子:
const chatReducer = (state = defaultState, action = {}) => {
const { type, payload } = action
switch (type) {
case ADD_CHAT:
return Object.assign({}, state, {
chatLog: state.chatLog.concat(payload)
})
case CHANGE_STATUS:
return Object.assign({}, state, {
statusMessage: payload
})
case CHANGE_USERNAME:
return Object.assign({}, state, {
userName: payload
})
default:
return state
}
}
上面代碼中,三種 Action 分別改變 State 的三個屬性:
- ADD_CHAT:chatLog 屬性
- CHANGE_STATUS:statusMessage 屬性
- CHANGE_USERNAME:userName 屬性
這三個屬性之間沒有聯繫,這提示我們可以把 Reducer 函數拆分。不同的函數負責處理不同屬性,最終把它們合併成一個大的 Reducer 即可。
const chatReducer = (state = defaultState, action = {}) => {
return {
chatLog: chatLog(state.chatLog, action),
statusMessage: statusMessage(state.statusMessage, action),
userName: userName(state.userName, action)
}
}
上面代碼中,Reducer 函數被拆成了三個小函數,每一個負責生成對應的屬性。
這樣一拆,Reducer 就易讀易寫多了。而且,這種拆分與 React 應用的結構相吻合:一個 React 根組件由很多子組件構成。這就是說,子組件與子 Reducer 完全可以對應。
Redux 提供了一個 combineReducers
方法,用於 Reducer 的拆分。只要定義各個子 Reducer 函數,然後用這個方法,將它們合成一個大的 Reducer。
import { combineReducers } from 'redux'
const chatReducer = combineReducers({
chatLog,
statusMessage,
userName
})
export default todoApp
上面的代碼通過 combineReducers
方法將三個子 Reducer 合併成一個大的函數。
這種寫法有一個前提,就是 State 的屬性名必須與子 Reducer 同名。如果不同名,就要採用下面的寫法。
const reducer = combineReducers({
a: doSomethingWithA,
b: processB,
c: c
})
// 等同於
function reducer(state = {}, action) {
return {
a: doSomethingWithA(state.a, action),
b: processB(state.b, action),
c: c(state.c, action)
}
}
總之,combineReducers()
做的就是產生一個整體的 Reducer 函數。該函數根據 State 的 key 去執行相應的子 Reducer,並將返回結果合併成一個大的 State 對象。
下面是 combineReducer
的簡單實現:
const combineReducers = (reducers) => {
return (state = {}, action) => {
return Object.keys(reducers).reduce((nextState, key) => {
nextState[key] = reducers[key](state[key], action)
return nextState
}, {})
}
}
可以把所有子 Reducer 放在一個文件裏面,然後統一引入:
import { combineReducers } from 'redux'
import * as reducers from './reducers'
const reducer = combineReducers(reducers)
五、工作流程
- 首先,用戶發出 Action:
store.dispatch(action)
- 然後,Store 自動調用 Reducer,並且傳入兩個參數:當前 State 和收到的 Action。 Reducer 會返回新的 State:
let nextState = todoApp(previousState, action)
- State 一旦有變化,Store 就會調用監聽函數:
// 設置監聽函數
store.subscribe(listener)
- listener 可以通過 store.getState() 得到當前狀態。如果使用的是 React,這時可以觸發重新渲染 View:
function listerner() {
let newState = store.getState()
component.setState(newState)
}
六、實例:計數器
const Counter = ({ value }) => <h1>{value}</h1>
const render = () => {
ReactDOM.render(
<Counter value={store.getState()} />,
document.getElementById('root')
)
}
store.subscribe(render)
render()
上面是一個簡單的計數器,唯一的作用就是把參數 value
的值,顯示在網頁上。Store 的監聽函數設置爲 render
,每次 State 的變化都會導致網頁重新渲染。
下面加入一點變化,爲 Counter
添加遞增和遞減的 Action。
const Counter = ({ value, onIncrement, onDecrement }) => (
<div>
<h1>{value}</h1>
<button onClick={onIncrement}>+</button>
<button onClick={onDecrement}>-</button>
</div>
)
const reducer = (state = 0, action) => {
switch (action.type) {
case 'INCREMENT':
return state + 1
case 'DECREMENT':
return state - 1
default:
return state
}
}
const store = createStore(reducer)
const render = () => {
ReactDOM.render(
<Counter
value={store.getState()}
onIncrement={() => store.dispatch({ type: 'INCREMENT' })}
onDecrement={() => store.dispatch({ type: 'DECREMENT' })}
/>,
document.getElementById('root')
)
}
render()
store.subscribe(render)