Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【109-110页】示例代码,浅响应没有调用track收集响应依赖 #16

Closed
YisenFE opened this issue Feb 21, 2022 · 1 comment
Closed

Comments

@YisenFE
Copy link

YisenFE commented Feb 21, 2022

浅响应不会执行 track 函数收集依赖,因此 target 本身的属性也不是响应式的
track 函数执行时机应在 if (isShallow) { ... } 判断语句之前

书上:

// 封装 createReactive 函数,接收一个参数 isShallow,代表是否为浅响应,默认为 false,即非浅响应
function createReactive(obj, isShallow = false) {
  return new Proxy(obj, {
    // 拦截读取操作
    get(target, key, receiver) {
      // 代理对象可以通过 raw 属性访问原始数据
      if (key === 'raw') {
        return target
      }

      const res = Reflect.get(target, key, receiver)
      // 如果是浅响应,则直接返回原始值
      if (isShallow) {
        return res
      }

      track(target, key)

      if (typeof res === 'object' && res !== null) {
        return reactive(res)
      }

      return res
    }
    // 省略其他拦截函数
  })
}

调整了下 track(target, key) 位置
修改后:

// 封装 createReactive 函数,接收一个参数 isShallow,代表是否为浅响应,默认为 false,即非浅响应
function createReactive(obj, isShallow = false) {
  return new Proxy(obj, {
    // 拦截读取操作
    get(target, key, receiver) {
      // 代理对象可以通过 raw 属性访问原始数据
      if (key === 'raw') {
        return target
      }
      track(target, key)

      const res = Reflect.get(target, key, receiver)
      // 如果是浅响应,则直接返回原始值
      if (isShallow) {
        return res
      }

      if (typeof res === 'object' && res !== null) {
        return reactive(res)
      }

      return res
    }
    // 省略其他拦截函数
  })
}
@HcySunYang
Copy link
Owner

#13
重复

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants