Redux 介紹 (二)
Action
Action 是把資料從介面或者伺服器端傳到 store 的有效載荷。它是 store 資料的唯一來源。
{
type: 'add',
name: 'newItem'
}
Action 本質上是 JavaScript 普通物件。redux約定,action 內必須使用一個字串型別的 type 欄位來表示將要執行的動作。多數情況下,type 會被定義成字串常量。當應用規模越來越大時,建議使用單獨的模組或檔案來存放 action。
Reducer
Reducers 指定了應用狀態的變化如何響應 actions 併發送到 store 的,記住 actions 只是描述了有事情發生了這一事實,並沒有描述應用如何更新 state。 reducer 就是一個純函式,接收舊的 state 和 action,返回新的 state。 在reducer 中不允許修改state,遇到未知的 action 時,一定要返回舊的 state
Store
Store 就是把action與reducer聯絡到一起的物件:
1. 維持應用的 state;
2. 提供 getState()
方法獲取 state;
3. 提供 dispatch(action)
方法更新 state;
4. 通過 subscribe(listener)
註冊監聽器;
5. 通過 subscribe(listener)
返回的函式登出監聽器
import { createStore } from 'redux'
import addfrom './reducers'
let store = createStore(add)
通過createStore()
reducer
建立
搭配React
react 搭配 redux 需要安裝 react-redux
npm install --save react-redux
Provider
react 使用 redux,需要在根節點外用 provider 包裹住,確保內部元件可以呼叫 connect()
方法。
該元件只有一個屬性 store,用於存放當前應用所使用的store。
展示元件和容器元件
通常我們所使用的元件都是展示型元件,但是,當我們需要將元件與redux的store聯絡起來的時候,就需要生成容器元件來監聽Redux state。
容器元件生成方式:
使用 React Redux 庫的connect()
shouldComponentUpdate()
方法進行效能優化。只有對應的store中的資料發生了變化,元件才會觸發重繪。