*Redux 是什麼
*Redux 的核心概念
*Redux 實戰
- readux 專注於狀態管理,和react 解耦
- 單一狀態,單向數據流
- 核心的概念:store ,state ,action ,reducer
- 人少的時候,無論是兵器還是人員的變更 ,都是setState
- 人多的時候,軍事和生活分開
- 所有狀態 歸redux管理,
- redux有一個 保險箱 (store),在那裏都有記錄,(state)
- 需要改變的時候,需要告訴專員 (dispatch)要幹什麼(action)
- 處理變化的人(reducer) ,拿到state 和 action ,生成新的state
Redux 的正確使用方法
- 首先通過reducer 新建store ,隨時通過store.getState獲取狀態
- 需要狀態變更,store.dispatch(action)來修改狀態
- Reducer函數 接受state和action ,返回新的state ,可以用store.subscribe,監聽每次修改.
Index.js
import { createStore } from "redux"
/*新建stoore
*通過reducer 建立
*根據老的狀態和action,生成新的state */
function counter (state=0,action){
switch(action.type){
case "加機關槍":
return state + 1
case "減機關槍":
return state - 1
default:
return 10
}
}
const store = createStore(counter)
/*新建store 結束*/
const init = store.getState()
console.log(init)