八、實(shí)現(xiàn)自己的 todolist

問題:

  1. 設(shè)置 style 不起作用
      <div style={{display: 'flex'}}>

原因我們節(jié)點(diǎn)的 style都有自己的引用,如果直接賦值替換的話不會(huì)生效,所以我們要在它原有的引用上修改

  Object.keys(nextProps).forEach(key => {
    if (key !== 'children') {
      if (nextProps[key] !== prevProps[key]) {
        // 不相等進(jìn)行更新賦值
        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]
          }
        }
      }
    }
  })
  1. 在 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 后會(huì)重新修改 wipRoot 和 nextWorkOfUnit 賦值,所以只要它有值了說明我們在 effectHooks 又改變了我們的 state,我們就應(yīng)該重新執(zhí)行 commitRoot

  if (!nextWorkOfUnit && wipRoot) {
    commitRoot()
  }
  if (nextWorkOfUnit && !wipRoot) {
    wipRoot = currentRoot
  }
  1. 直接使用 map 不需要解構(gòu)
    我們現(xiàn)在想要使用 map 智能解構(gòu),因?yàn)槲覀儧]對(duì)數(shù)組進(jìn)行處理,想要直接使用可以在 遍歷 children 節(jié)點(diǎn)的時(shí)候或者 crateElement 的時(shí)候處理
    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)
    }
  }
}
  1. 在遍歷 children 節(jié)點(diǎn)的時(shí)候
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) => {``

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容