1吨娜、高階組件是一個(gè)函數(shù),接受一個(gè)組件作為參數(shù)淘钟,返回一個(gè)新的組件宦赠。新的組件使用傳入的組件作為子組件。
1.1米母、高階組件的作用其實(shí)不言而喻袱瓮,其實(shí)就是為了組件之間的代碼復(fù)用。組件可能有著某些相同的邏輯爱咬,把這些邏輯抽離出來尺借,放到高階組件中進(jìn)行復(fù)用。高階組件內(nèi)部的包裝組件和被包裝組件之間通過 props 傳遞數(shù)據(jù)精拟。
2燎斩、React.js 的 context 其實(shí)像就是組件樹上某顆子樹的全局變量(狀態(tài)管理插件中使用)虱歪。
2.1、父組件中
static childContextTypes = {
themeColor: PropTypes.string
}
getChildContext () {
return { themeColor: this.state.themeColor }
}
子組件中
static contextTypes = {
themeColor: PropTypes.string
}
this.context.themeColor 調(diào)用
3栅表、redux的學(xué)習(xí)
3.1笋鄙、矛盾:“模塊(組件)之間需要共享數(shù)據(jù)”,和“數(shù)據(jù)可能被任意修改導(dǎo)致不可預(yù)料的結(jié)果”之間的矛盾怪瓶。
解決:dispatch(action) 負(fù)責(zé)修改數(shù)據(jù)
所有對數(shù)據(jù)的操作必須通過 dispatch 函數(shù)萧落。
const store=createStore(state,stateChanger){
const getState=()=>state;
const dispatch=(action)=>stateChanger(state,action);
return {getState,dispatch}
}
3.2、解決數(shù)據(jù)自動(dòng)更新洗贰,引入訂閱者模式
store.subscribe(()=>render(state));
3.3找岖、條件性渲染
state+stateChanger==reducer,reducer負(fù)責(zé)初始化state或者根據(jù)state,action產(chǎn)生新的state。
3.4敛滋、// 定一個(gè) reducer
function reducer (state, action) {
/* 初始化 state 和 switch case */
}
// 生成 store
const store = createStore(reducer)
// 監(jiān)聽數(shù)據(jù)變化重新渲染頁面
store.subscribe(() => renderApp(store.getState()))
// 首次渲染頁面
renderApp(store.getState())
// 后面可以隨意 dispatch 了许布,頁面自動(dòng)更新
store.dispatch(...)
React.js 小書地址:http://huziketang.mangojuice.top/books/react