React 只是 DOM 的一個抽象層,并不是 Web 應用的完整解決方案。有兩個方面,它沒涉及。
* 代碼結構
* 組件之間的通信
對于大型的復雜應用來說,這兩方面恰恰是最關鍵的。因此,只用 React 沒法寫大型應用。
Redux是Flux和函數式編程結合在一起的產物。
***
1.簡單說,如果你的UI層非常簡單,沒有很多互動,Redux 就是不必要的,用了反而增加復雜性。
```
* 用戶的使用方式非常簡單
* 用戶之間沒有協作
* 不需要與服務器大量交互,也沒有使用 WebSocket
* 視圖層(View)只從單一來源獲取數據
```
上面這些情況,都不需要使用 Redux。
```
* 用戶的使用方式復雜
* 不同身份的用戶有不同的使用方式(比如普通用戶和管理員)
* 多個用戶之間可以協作
* 與服務器大量交互,或者使用了WebSocket
* View要從多個來源獲取數據
```
上面這些情況才是 Redux 的適用場景:多交互、多數據源。
從組件角度看,如果你的應用有以下場景,可以考慮使用 Redux。
```
* 某個組件的狀態,需要共享
* 某個狀態需要在任何地方都可以拿到
* 一個組件需要改變全局狀態
* 一個組件需要改變另一個組件的狀態
```
## 二、設計思想
```
(1)Web 應用是一個狀態機,視圖與狀態是一一對應的。
(2)所有的狀態,保存在一個對象里面。
```
## 三、基本概念和 API
### 3.1 Store
Store 就是保存數據的地方,你可以把它看成一個容器。整個應用只能有一個 Store。
Redux 提供`createStore`這個函數,用來生成 Store。
~~~javascript
import { createStore } from 'redux';
const store = createStore(fn);
~~~
### 3.2 State
`Store`對象包含所有數據。如果想得到某個時點的數據,就要對 Store 生成快照。這種時點的數據集合,就叫做 State。
當前時刻的 State,可以通過`store.getState()`拿到。
~~~javascript
import { createStore } from 'redux';
const store = createStore(fn);
const state = store.getState();
~~~
>Redux 規定, 一個 State 對應一個 View。只要 State 相同,View 就相同。你知道 State,就知道 View 是什么樣,反之亦然。
### 3.3 Action
State 的變化,會導致 View 的變化。但是,用戶接觸不到 State,只能接觸到 View。所以,State 的變化必須是 View 導致的。Action 就是 View 發出的通知,表示 State 應該要發生變化了。
Action 是一個對象。其中的`type`屬性是必須的,表示 Action 的名稱。其他屬性可以自由設置,社區有一個[規范](https://github.com/acdlite/flux-standard-action)可以參考。
~~~javascript
const action = {
type: 'ADD_TODO',
payload: 'Learn Redux'
};
~~~
上面代碼中,Action 的名稱是`ADD_TODO`,它攜帶的信息是字符串`Learn Redux`。
可以這樣理解,Action 描述當前發生的事情。改變 State 的唯一辦法,就是使用 Action。它會運送數據到 Store。
### 3.4Action Creator
View要發送多少種信息,就會有多少種Action。可以定義一個函數來生成Action,這個函數就是Action Creator.
~~~javascript
const ADD_TODO = '添加 TODO';
function addTodo(text) {
return {
type: ADD_TODO,
text
}
}
const action = addTodo('Learn Redux');
~~~
上面代碼中,`addTodo`函數就是一個 Action Creator。
### 3.5 store.dispatch()
`store.dispatch()`是 View 發出 Action 的唯一方法。
~~~javascript
import { createStore } from 'redux';
const store = createStore(fn);
store.dispatch({
type: 'ADD_TODO',
payload: 'Learn Redux'
});
~~~
上面代碼中,`store.dispatch`接受一個 Action 對象作為參數,將它發送出去。
結合 Action Creator,這段代碼可以改寫如下。
~~~javascript
store.dispatch(addTodo('Learn Redux'));
~~~
## 3.6 Reducer
Store 收到 Action 以后,必須給出一個新的 State,這樣 View 才會發生變化。這種 State 的計算過程就叫做 Reducer。
Reducer 是一個函數,它接受 Action 和當前 State 作為參數,返回一個新的 State。
~~~javascript
const reducer = function (state, action) {
// ...
return new_state;
};
~~~
整個應用的初始狀態,可以作為 State 的默認值。下面是一個實際的例子。
~~~javascript
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`方法。
~~~javascript
import { createStore } from 'redux';
const store = createStore(reducer);
~~~
上面代碼中,`createStore`接受 Reducer 作為參數,生成一個新的 Store。以后每當`store.dispatch`發送過來一個新的 Action,就會自動調用 Reducer,得到新的 State。
### 3.7 純函數
Reducer 函數最重要的特征是,它是一個純函數。也就是說,只要是同樣的輸入,必定得到同樣的輸出。
純函數是函數式編程的概念,必須遵守以下一些約束。
* 不得改寫參數
* 不能調用系統 I/O 的API
* 不能調用`Date.now()`或者`Math.random()`等不純的方法,因為每次會得到不一樣的結果
由于 Reducer 是純函數,就可以保證同樣的State,必定得到同樣的 View。但也正因為這一點,Reducer 函數里面不能改變 State,必須返回一個全新的對象,請參考下面的寫法。
~~~javascript
// 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 總是一個不變的對象。
### 3.8 store.subscribe()
Store 允許使用`store.subscribe`方法設置監聽函數,一旦 State 發生變化,就自動執行這個函數。
~~~javascript
import { createStore } from 'redux';
const store = createStore(reducer);
store.subscribe(listener);
~~~
顯然,只要把 View 的更新函數(對于 React 項目,就是組件的`render`方法或`setState`方法)放入`listen`,就會實現 View 的自動渲染。
`store.subscribe`方法返回一個函數,調用這個函數就可以解除監聽。
~~~javascript
let unsubscribe = store.subscribe(() =>
console.log(store.getState())
);
unsubscribe();
~~~
## 四、Store 的實現
上一節介紹了 Redux 涉及的基本概念,可以發現 Store 提供了三個方法。
* store.getState()
* store.dispatch()
* store.subscribe()
~~~javascript
import { createStore } from 'redux';
let { subscribe, dispatch, getState } = createStore(reducer);
~~~
`createStore`方法還可以接受第二個參數,表示 State 的最初狀態。這通常是服務器給出的。
~~~javascript
let store = createStore(todoApp, window.STATE_FROM_SERVER)
~~~
上面代碼中,`window.STATE_FROM_SERVER`就是整個應用的狀態初始值。注意,如果提供了這個參數,它會覆蓋 Reducer 函數的默認初始值。
下面是`createStore`方法的一個簡單實現,可以了解一下 Store 是怎么生成的。
~~~javascript
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 函數也十分龐大。
eg:
~~~javascript
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 即可。
~~~javascript
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。
~~~javascript
import { combineReducers } from 'redux';
const chatReducer = combineReducers({
chatLog,
statusMessage,
userName
})
export default todoApp;
~~~
上面的代碼通過`combineReducers`方法將三個子 Reducer 合并成一個大的函數。
這種寫法有一個前提,就是 State 的屬性名必須與子 Reducer 同名。如果不同名,就要采用下面的寫法。
~~~javascript
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`的簡單實現。
~~~javascript
const combineReducers = reducers => {
return (state = {}, action) => {
return Object.keys(reducers).reduce(
(nextState, key) => {
nextState[key] = reducers[key](state[key], action);
return nextState;
},
{}
);
};
};
~~~
你可以把所有子 Reducer 放在一個文件里面,然后統一引入。
~~~javascript
import { combineReducers } from 'redux'
import * as reducers from './reducers'
const reducer = combineReducers(reducers)
~~~
## 六、工作流程
本節對 Redux 的工作流程,做一個梳理。

首先,用戶發出 Action。
~~~javascript
store.dispatch(action);
~~~
然后,Store 自動調用 Reducer,并且傳入兩個參數:當前 State 和收到的 Action。 Reducer 會返回新的 State 。
~~~javascript
let nextState = todoApp(previousState, action);
~~~
State 一旦有變化,Store 就會調用監聽函數。
~~~javascript
// 設置監聽函數
store.subscribe(listener);
~~~
`listener`可以通過`store.getState()`得到當前狀態。如果使用的是 React,這時可以觸發重新渲染 View。
~~~javascript
function listerner() {
let newState = store.getState();
component.setState(newState);
}
~~~
- React進階
- React進階-組件 & Props
- React進階-組件 & Props - 代碼篇
- 組件擴展-組件生命周期
- 組件擴展-組件生命周期-代碼篇
- React-Redux
- Redux入門教程-基本用法
- Redux入門教程-基本用法-代碼篇
- Redux入門教程-中間件和異步操作
- Redux入門教程-React-Redux 的用法
- Redux入門教程-React-Redux的用法-代碼篇
- ES6-變量的解構賦值
- 數組的解構賦值
- 對象的解構賦值
- React用法
- JSX技巧
- ES6-神奇的...
- yarn+webpack+react零基礎創建項目
- 0-init
- 1-webpack.config.md
- 2-react相關依賴
- 3.編寫react相關代碼
- pnpx-react-config
- pnpx+create-react
- pnpm+react-config
- pnpm+react-antd