redux的適用場景
頁面有很多交互,
有太多props需要在組件樹中傳遞
一個(gè)頁面有多個(gè)ajax
下面是redux的流程圖

redux的組成
Action 事件?
本質(zhì)上就是一個(gè)JS對象 必須包含type屬性,只是描述了有事情要發(fā)生,并沒有描述如何去更新state,傳遞給reducer改更新的state
Reducer?
本質(zhì)就是函數(shù),Reducecr中是更改store中數(shù)據(jù)的stare返回一個(gè)新的stare 來完成視圖的更新
Store
簡單來說用來把a(bǔ)ction和reducer關(guān)聯(lián)到一起,store就是redux的一個(gè)數(shù)據(jù)中心,store就是用來存儲(chǔ)數(shù)據(jù)state的,從中取出對應(yīng)的數(shù)據(jù)。因此最開始,我們要?jiǎng)?chuàng)建一個(gè)這樣的store,redux提供了createStore方法。
store通過subscribe來注冊監(jiān)聽? ? ? ? ? ? ?通過dispatch來發(fā)送action到達(dá)reducer
如何更改/獲取redux數(shù)據(jù)
更改數(shù)據(jù)store.dispatch(action)
在組件中使用
const action ={
type:'NUM',
num:count (count是需要執(zhí)行的函數(shù))
}
store.dispatch(action) 組件中也是主要使用subscribe來監(jiān)聽 store store發(fā)生數(shù)據(jù)變化視圖就會(huì)更新
在store中定義數(shù)據(jù)庫
在reducer中 定義num 的值 定義 (state = num,action) 通過type值來執(zhí)行相對的操作
當(dāng)你更改數(shù)據(jù)時(shí) 去
可以使用connect更改redux數(shù)據(jù)
獲取數(shù)據(jù) store.getState()
在 store文件中 使用 store = createStore(reducer) 創(chuàng)建數(shù)據(jù)存儲(chǔ)庫
在Reducer 文件 可以定義一個(gè)數(shù)據(jù) const book1= {value: '這是數(shù)據(jù)'}
function state(state = defaultState,action){return state}
最后return導(dǎo)入
組件中 先import引入store 使用 store.getState() 可以獲取到redux存儲(chǔ)的數(shù)據(jù)