問題:
- 設(shè)置 style 不起作用
<div style={{display: 'flex'}}>
原因我們節(jié)點的 style都有自己的引用,如果直接賦值替換的話不會生效,所以我們要在它原有的引用上修改
Object.keys(nextProps).forEach(key => {
if (key !== 'children') {
if (nextProps[key] !== prevProps[key]) {
// 不相等進行更新賦值
const isEvent = key.startsWith('on')
if (isEvent) {
const eventType = key.slice(2).toLocaleLowerCase()
dom.removeEventListener(eventType, prevProps[key])
dom.addEventListener(eventType, nextProps[key])
} else {
+ if (key === 'style') {
+ Object.assign(dom[key], nextProps[key])
+ } else {
dom[key] = nextProps[key]
}
}
}
}
})
- 在 useEffect 里修改 state 頁面沒更新
React.useEffect(() => {
if (checkedValue === 'all') {
setDisplayList(list)
} else {
const newList = list.filter(item => item.status === checkedValue)
setDisplayList(newList)
}
console.log(list, 'hhhhdd')
}, [list, checkedValue])
<div>{
...displayList.map((item) => (...)}</div>
原因:
我們先去調(diào)用了 commitWork 將視圖更新完,再調(diào)用 commitEffectHooks,所以雖然我們的數(shù)據(jù)變了但是視圖沒有改變
解決方案:
在 commitEffectHooks 后重新調(diào)用 commitWork
所以我們?nèi)タ次覀兊?useState 它在 setState 后會重新修改 wipRoot 和 nextWorkOfUnit 賦值,所以只要它有值了說明我們在 effectHooks 又改變了我們的 state,我們就應(yīng)該重新執(zhí)行 commitRoot
if (!nextWorkOfUnit && wipRoot) {
commitRoot()
}
if (nextWorkOfUnit && !wipRoot) {
wipRoot = currentRoot
}
- 直接使用 map 不需要解構(gòu)
我們現(xiàn)在想要使用 map 智能解構(gòu),因為我們沒對數(shù)組進行處理,想要直接使用可以在 遍歷 children 節(jié)點的時候或者 crateElement 的時候處理
1). 在 createElement 處理
const createElement = (type, props, ...children) => {
// 不管是 [[{type: 'div'}]] 還是 [{type: 'div'}] 都給他拍平成 [{type: 'div'}]
const newChildren = children.flat()
return {
type,
props: {
...props,
children: newChildren.map(child => ['string', 'number'].includes(typeof child) ? createTextNode(child) : child)
}
}
}
- 在遍歷 children 節(jié)點的時候
const initChildren = (fiber, children) => {
let oldFiber = fiber.alternate?.child
let prevChild = null
// [{type: 'div'}] / [[{type: 'div'}, {type: 'div'}]]
const newChildren = children.flat()
newChildren.forEach((child, index) => {``