• js react源码中seal和freeze的使用


    定义与区别

    seal: 封闭。只允许操作入参对象原本就可写的属性
    freeze: 冻结,不允许操作所有属性,包括原型与原型链


    应用

    React源码,开发模式下
    初次渲染,ref会被赋值为一个具有current的seal对象,而props.children则是一个childArray的冻结对象

    freeze usage

      // Children can be more than one argument, and those are transferred onto
      // the newly allocated props object.
      const childrenLength = arguments.length - 2;
      if (childrenLength === 1) {
        props.children = children;
      } else if (childrenLength > 1) {
        const childArray = Array(childrenLength);
        for (let i = 0; i < childrenLength; i++) {
          childArray[i] = arguments[i + 2];
        }
        if (__DEV__) {
          if (Object.freeze) {
            Object.freeze(childArray);
          }
        }
        props.children = childArray;
      }
    

    ref usage

    export function useRef<T>(initialValue: T): {current: T} {
      currentlyRenderingFiber = resolveCurrentlyRenderingFiber();
      workInProgressHook = createWorkInProgressHook();
      let ref;
      
      // 初次渲染,直接赋值为{current: initialValue},并使用seal封闭,并初始化workInProgressHook.memoizedState
      if (workInProgressHook.memoizedState === null) {
        ref = {current: initialValue};
        if (__DEV__) {
          Object.seal(ref);
        }
        workInProgressHook.memoizedState = ref;
      } 
      // 组件更新
      else {
        ref = workInProgressHook.memoizedState;
      }
      return ref;
    }
    
  • 相关阅读:
    《构建之法》阅读报告
    教务管理系统类图及数据库E/R图
    设计模式:抽象工厂
    结对项目:四则运算程序测试
    Leetcode笔记之57和为s的连续正数序列
    Leetcode笔记之1103分糖果 II
    Leetcode笔记之199二叉树的右视图
    每日Scrum(9)
    每日Scrum(7)
    每日Scrum(6)
  • 原文地址:https://www.cnblogs.com/ltfxy/p/16042254.html
Copyright © 2020-2023  润新知