Análisis del código fuente de Redux - 1, suscribirse, darse de baja

suscripción

Todo el código, no mucho.

function subscribe(listener: () => void) {
    
    
  //参数不是函数,报错。
  if (typeof listener !== 'function') {
    
    
    throw new Error(
      `Expected the listener to be a function. Instead, received: '${
      
      kindOf(
        listener
      )}'`
    )
  }
  //是否正在执行中
  if (isDispatching) {
    
    
    throw new Error(
      'You may not call store.subscribe() while the reducer is executing. ' +
      'If you would like to be notified after the store has been updated, subscribe from a ' +
      'component and invoke store.getState() in the callback to access the latest state. ' +
      'See https://redux.js.org/api/store#subscribelistener for more details.'
    )
  }
  //打开标记,是订阅
  let isSubscribed = true
  //确保next和current不是同一个对象
  ensureCanMutateNextListeners()
  //next添加
  nextListeners.push(listener)
  //返回函数,取消订阅
  return function unsubscribe() {
    
    
  //...
  }
}

1. Determinar los parámetros. Si no es una función, se informa de un error.

if (typeof listener !== 'function') {
    
    
  throw new Error(
    `Expected the listener to be a function. Instead, received: '${
      
      kindOf(
      listener
    )}'`
  )
}

2. Si se está ejecutando, se informará de un error.

if (isDispatching) {
    
    
  throw new Error(
    'You may not call store.subscribe() while the reducer is executing. ' +
    'If you would like to be notified after the store has been updated, subscribe from a ' +
    'component and invoke store.getState() in the callback to access the latest state. ' +
    'See https://redux.js.org/api/store#subscribelistener for more details.'
  )
}

3, abra la marca, es suscribirse.

let isSubscribed = true

4. Asegúrese de que el siguiente y el actual no sean el mismo objeto.

Si es así, el actual se copia al siguiente.

ensureCanMutateNextListeners()

function ensureCanMutateNextListeners() {
    
    
  if (nextListeners === currentListeners) {
    
    
    nextListeners = currentListeners.slice()
  }
}

5, se agrega la siguiente matriz

nextListeners.push(listener)

6. Devuelve la función para cancelar la suscripción.

return function unsubscribe() {
    
    
	//...
}

darse de baja

También muy conciso.

return function unsubscribe() {
    
    
  //没订阅直接返回
  if (!isSubscribed) {
    
    
    return
  }
  //是否正在执行中
  if (isDispatching) {
    
    
    throw new Error(
      'You may not unsubscribe from a store listener while the reducer is executing. ' +
      'See https://redux.js.org/api/store#subscribelistener for more details.'
    )
  }
  //变成无订阅状态
  isSubscribed = false
  //确保next和current不是一个对象
  ensureCanMutateNextListeners()
  //获取当前订阅者的索引
  const index = nextListeners.indexOf(listener)
  //切掉它
  nextListeners.splice(index, 1)
  //清除缓存
  currentListeners = null
}

1. No es una devolución directa de suscripción.

Esta bandera se activa al suscribirse.

if (!isSubscribed) {
    
    
  return
}

2. Si se está ejecutando, se informará de un error.

if (isDispatching) {
    
    
  throw new Error(
    'You may not unsubscribe from a store listener while the reducer is executing. ' +
    'See https://redux.js.org/api/store#subscribelistener for more details.'
  )
}

3. Cierra la marca.

isSubscribed = false

4. Asegúrate nuevamente de que no es el mismo objeto.

ensureCanMutateNextListeners()

5. La siguiente matriz elimina elementos.

//获取当前订阅者的索引
const index = nextListeners.indexOf(listener)
//切掉它
nextListeners.splice(index, 1)

6, asignación actual nula

currentListeners = null

Análisis de Operaciones Críticas

1, suscribirse, darse de baja

Suscribirse: Agregar matriz.
Darse de baja: Eliminación de matriz.

Es un poco como este artículo: https://blog.csdn.net/qq_37284843/article/details/123361179
(comunicación manuscrita entre componentes)

2. Marca de suscripción

Etiqueta abierta al suscribirse.

Juez al darse de baja:
cerrar: volver directamente.
No cerrado: interruptor para cerrar, la operación de cierre posterior.

Esto es lo suficientemente inteligente como para hacer que cancelar la suscripción solo se active una vez.

3. Marca en ejecución

isDispatching

A juzgar al suscribirse, true informará un error.
Juzguelo al cancelar, true informará un error.

4. Doble búfer

Asegúrese repetidamente de que el siguiente y el actual no sean el mismo objeto:

ensureCanMutateNextListeners()

function ensureCanMutateNextListeners() {
    
    
  if (nextListeners === currentListeners) {
    
    
    nextListeners = currentListeners.slice()
  }
}

Cada vez que la actual se copia a la siguiente.

siguiente: responsable de la modificación.
Agregar y quitar, es operarlo.

actual: responsable de la consulta.
No se usa aquí y se le asigna un valor nulo al final.

Supongo que te gusta

Origin blog.csdn.net/qq_37284843/article/details/123642825
Recomendado
Clasificación