代碼地址
https://github.com/iosKey/miniReact
核心方法
setState方法(把state和callback添加到隊(duì)列中批量執(zhí)行)
new Updater,把setState里面的state和callback方法放到2個(gè)數(shù)組中
emitUpdate
外界也可以通過(guò)獲取組件的updater執(zhí)行的 馬上出發(fā)更新器的updateComponent方法,props或state改變了就會(huì)走更新
updateComponent
更新組件 拿到最新的props state context
getState
遍歷states數(shù)組(后面的值會(huì)覆蓋前面相同的key值) 拿到最新的state 如果遍歷到的是function报破,執(zhí)行這個(gè)function傳入state和props
shouldUpdate
shouldComponentUpdate默認(rèn)為true 渲染界面 如果組件重寫(xiě)的shouldComponentUpdate就執(zhí)行以下該鉤子函數(shù)拿到最新的值 false的話只更新以下組件的屬性值(props state context cache),不往下更新界面
forceUpdate
更新props state context cache 判斷一下組件掛載沒(méi)有 掛載往下執(zhí)行 如果存在componentWillUpdate方法就執(zhí)行它
renderComponent 實(shí)際上是調(diào)用了component.render方法創(chuàng)建了虛擬dom 作為新虛擬節(jié)點(diǎn)跟緩存的舊節(jié)點(diǎn)做比較
compareTwoVnodes
1 如果新節(jié)點(diǎn)是空的 刪除虛擬dom上舊節(jié)點(diǎn)(根據(jù)原生標(biāo)簽 function組件 class組件分為不同的刪除方法)遍歷children刪除 再刪除真實(shí)dom節(jié)點(diǎn)
2比較新舊節(jié)點(diǎn)的標(biāo)簽名或新舊節(jié)點(diǎn)的key 做替換操作 刪除虛擬dom上舊節(jié)點(diǎn) 生成一個(gè)最新dom節(jié)點(diǎn) 新節(jié)點(diǎn)替換舊節(jié)點(diǎn)
3相同類(lèi)型的標(biāo)簽 或 相同的key比較 根據(jù)不同type做對(duì)應(yīng)的更新屬性的操作 最后走diff比較children