一、執行流程
全局有一個公共的容器(所有組件都可以操作),我們可以在某個組件中把全局容器中的信息進行修改,而只要全局信息修改,就可以通知所有用到該信息的組件重新渲染(類似於發布訂閱)==》redux就是這種解決方案:redux只有一個作用,就是為了實現組件之間的信息交互。
1.執行createStore
- 創建一個容器store來用來管理公用的狀態信息
- 創建一個事件池,用來存儲一些方法(方法一般都是用來通知某個組件重新渲染的)
- 當容器中的狀態改變,會自動通知事件池中的方法依次執行
2.基於store.getState可以獲取容器中存儲的狀態信息(拿到狀態信息就可以做數據綁定等操作了)
3.我們可以基於store.subscribe向事件池中追加方法(也可以移除事件池中的方法)
4.修改容器中的狀態信息
- 首先雇一個管理員reducer,它就是用來修改容器中狀態的
- 當我們在組件中進行某些操作想要修改狀態信息的時候,我們首先dispatch派發一個任務給reducer,並且告訴reducer如何去修改狀態信息
公共狀態信息都是reducer去改的,reducer記錄了所有修改狀態的行為方式,我們以后想要知道怎么改的狀態,只要看reducer即可。
- redux:不局限於任何框架(vue/react/angular/jquery...)
- react-redux:把redux進一步封裝,專門給react框架開發的(操作起來更簡潔)
- vuex:類似於redux的操作思想,專門為vue框架定制的
- dva:把redux/react-redux進一步封裝,操作更簡潔
- mobx:和redux不完全一致,也是用來管控公共狀態的,只不過操作起來更加簡單而已
畫一張簡易流程圖
2.具體代碼
App.js import {createStore} from 'redux' /** * 創建redux容器用力啊管理公共的狀態信息 * 1.創建容器的時候其實已經准備好了管理員reducer了 * 2.createStore(reducer):相當於創建一個容器並雇佣了一個管理員reducer * 3.創建出來的store存在幾個屬性:getState/dispatch/subscribe */ let store = createStore(reducer); window.store = store; //把創建的容器掛載到全局下,保證每一個子組件都可以獲取到store,從而執行一些其它的操作(當然也可以基於屬性) //reducer管理員是一個方法:reducer方法是在dispatch派發的時候執行的 //state:現有store容器中的狀態信息(如果store中沒有,我們給一個初始值) //action: 告訴reduce如何去修改狀態都在action中(它是一個對象,對象中固定的有type屬性:派發任務的行為標識,reducer就是根據不同的行為標識來修改狀態信息的) function reducer(state = { n: 0, m: 0 }, action) { //reducer就是根據不同的行為標識來修改狀態信息的 switch (action.type) { case 'support': state.n = state.n+1;break; case 'against': state.m = state.m+1;break; } return state; //return的是什么,就會把store中的狀態改成什么 } <Vote></Vote> //調用 vote.js import React from 'react'; import VoteHeader from './voteHeader.js' import VoteBody from './voteBody.js' import VoteFooter from './voteFooter.js' class Vote extends React.Component{ constructor(){ super() } render() { return ( <div> <VoteBody></VoteBody> <VoteFooter></VoteFooter> </div> ) } } export default Vote; voteBody.js import React from 'react'; class VoteBody extends React.Component{ constructor(){ super() } componentDidMount() { //通過subscribe追加事件,進行強制更新 window.store.subscribe(()=>{ this.forceUpdate(); }) } render() { //獲取狀態的改變 let {n, m} = window.store.getState(); return ( <div> <div>贊成{n}票</div> <div>反對{m}票</div> </div> ) } } export default VoteBody; voteFooter.js import React from 'react'; class VoteFooter extends React.Component{ constructor(){ super() } render() { let store = window.store; return ( <div> //通過dispatch通知reducer根據不同的標示修改不同的狀態 <button onClick={e => store.dispatch({type: 'support'})}>贊成</button> <button onClick={e => store.dispatch({type: 'against'})}>反對</button> </div> ) } } export default VoteFooter;