1).統一資料管理
將所需的資料提取到state中統一進行管理。當渲染後我們希望更改狀態,封裝更改狀態的方法(dispatch)
2).實現dispatch
不要直接更改狀態而是使用dispatch方法進行狀態的更改,派發乙個帶有type的屬性來進行狀態的更改,但是依然無法阻止使用者更改狀態.
3).createstore的實現
將狀態放到了createstore函式中,目的是隔離作用域,並且再內部返回深度轉殖的物件,這樣使用者無法再通過外界更改狀態。但是狀態應該由我們自身來控制,應該是外界傳入的,所以要將狀態拿出createstore。並且判斷的邏輯也應該由我們自己來編寫
4).reducer的實現
我們已將需要自己處理的邏輯提取出來,但是我們每次dispatch時都需要自己觸發檢視的更新,我們希望採用發布訂閱來實現。
5).訂閱函式
我們redux中常用的方法已經封裝完成我們將封裝好的邏輯抽離成redux.js
2.1 redux檔案拆分store
│ action-types.js
│ index.js
│├─actions
│ counter.js
│└─reducer
counter.js
action-types用來存放需要的常量
counter中存放reducer的邏輯
store中的index檔案用來建立store
action資料夾中的counter,用來生成對應元件的action物件
2.2 實現多個counter在redux中只能擁有乙個store所以我們需要將多個狀態進行合併,狀態是通過reducer返回的,所以我們可以將多個reducer進行合併達到合併狀態的目的。
│ index.js
│ redux.js
│ ├─components
│ counter1.js
│ counter2.js
│ └─store
│ action-types.js
│ index.js
│├─actions
│ counter1.js
│ counter2.js
│└─reducer
counter1.js
counter2.js
index.js
action-types新增counter2處理的常量
對應的counter2中的action也進行更改
1.為什麼需要高階元件
從本地儲存中獲取資料放到輸入框內的邏輯應該就是公用邏輯。這時我們就要使用高階元件,也就是將元件在原有的基礎上進行包裝。
2.實現高階元件
我們將公共的邏輯拿到外層元件,處理好後以屬性的方式傳遞給原本的元件,為此高階元件就是乙個 react 元件包裹著另外乙個 react 元件
3.context的用法
react是單向資料流,我們想傳遞資料需要一層層向下傳遞,資料傳遞變得非常麻煩,我們可以用context實現資料的互動
1) 父 childcontexttypes getchildcontext函式
2) 子 contexttypes
import react from
'react'
;import reactdom from
'react-dom'
;import counter from
"./components/counter"
;import store from
'./store/index'
;import
from
'react-redux'
;reactdom.
render
(>
>
<
/provider>
,window.root)
;// counter元件
class
counter
extends
react.component
}>
+<
/button>
}>
-<
/button>
<
/div>}}
export
default
connect
(state=>()
,dispatch=>(,
minus:
(amount)
=>})
)(counter)
1.logger中介軟體
在控制台檢視更改前後的狀態
2.實現redux-thunk中介軟體
實現派發非同步動作,actioncreator可以返回函式,可以把dispatch的許可權交給此函式
3.實現redux-promise中介軟體
返回乙個例項 ,支援非同步請求 看resolve reject情況
"title"
>
<
/div>
"content"
>
<
/div>
// state getstate dispatch subscribe
// subscribe : 訂閱;可以訂閱一些方法,當執行完dispatch之後,會把訂閱的方法執行
const
change_title_text
="change_title_text"
;const
change_content_color
="change_content_color"
;function
createstore
(reducer)})
}dispatch()
;function
subscribe
(fn)
}return
}let initstate =
, content:};
function
reducer
(state = initstate, action)};
case
change_content_color
:return}}
return state;
}let store =
createstore
(reducer)
;function
rendertitle()
function
rendercontent()
function()
();settimeout
(function()
);store.
dispatch()
},2000
)// f();// 取消訂閱
redux基本使用
actiontype.js 隨著專案大型化,所以要抽取出來乙個actiontype.js檔案來記錄各種actiontype常量 export const set currentindex set currentindex store.js import from redux import rootr...
Redux基本使用(一)
redux基礎 一 設計思想 react是單項資料流框架,為了在相對較大的專案中方便進行狀態管理。二 基本概念 1.store 儲存資料並且是改變state的地方,用createstore來進行建立。整個應用只能有乙個 import from redux createstore函式用來接收reduc...
Redux基本原理和使用
redux不是說任何的應用都要用到它,如果遇到了react解決不了得問題,可以考慮使用它。例如 使用者的使用方式複雜 不同身份的使用者有不同的使用方式 比如普通使用者和管理員 多個使用者之間可以協作 與伺服器大量互動,或者使用了websocket view要從多個 獲取資料 redux的設計思想 1...