Redux源码分析——2,发出更新请求

2022/3/21 20:27:34

本文主要是介绍Redux源码分析——2,发出更新请求,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

文章目录

  • 发出更新请求

发出更新请求

代码也很少。

function dispatch(action: A) {
  if (!isPlainObject(action)) {
    throw new Error(
      `Actions must be plain objects. Instead, the actual type was: '${kindOf(
        action
      )}'. You may need to add middleware to your store setup to handle dispatching other values, such as 'redux-thunk' to handle dispatching functions. See https://redux.js.org/tutorials/fundamentals/part-4-store#middleware and https://redux.js.org/tutorials/fundamentals/part-6-async-logic#using-the-redux-thunk-middleware for examples.`
    )
  }
  if (typeof action.type === 'undefined') {
    throw new Error(
      'Actions may not have an undefined "type" property. You may have misspelled an action type string constant.'
    )
  }
  if (isDispatching) {
    throw new Error('Reducers may not dispatch actions.')
  }
  try {
    isDispatching = true
    currentState = currentReducer(currentState, action)
  } finally {
    isDispatching = false
  }
  const listeners = (currentListeners = nextListeners)
  for (let i = 0; i < listeners.length; i++) {
    const listener = listeners[i]
    listener()
  }
  return action
}

1,如果参数不是简单的对象,报错。

何为简单的对象?
原型为null,由字面量声明。

这种算法适用性更广。

if (!isPlainObject(action)) {
  throw new Error(
    `Actions must be plain objects. Instead, the actual type was: '${kindOf(
      action
    )}'. You may need to add middleware to your store setup to handle dispatching other values, such as 'redux-thunk' to handle dispatching functions. See https://redux.js.org/tutorials/fundamentals/part-4-store#middleware and https://redux.js.org/tutorials/fundamentals/part-6-async-logic#using-the-redux-thunk-middleware for examples.`
  )
}

function isPlainObject(obj: any): boolean {
  if (typeof obj !== 'object' || obj === null) return false
  let proto = obj
  while (Object.getPrototypeOf(proto) !== null) {
    proto = Object.getPrototypeOf(proto)
  }
  return Object.getPrototypeOf(obj) === proto
}

2,没有type属性,报错。

所以,Action必须要有type属性。

if (typeof action.type === 'undefined') {
  throw new Error(
    'Actions may not have an undefined "type" property. You may have misspelled an action type string constant.'
  )
}

3,正在执行中,报错。

if (isDispatching) {
  throw new Error('Reducers may not dispatch actions.')
}

4,调用Reducer。

打开标记。
调用reducer,传入前状态,action。
返回新状态。

完毕后关闭标记。

try {
  isDispatching = true
  currentState = currentReducer(currentState, action)
} finally {
  isDispatching = false
}

5,通知所有粉丝。

从next中拿current,再查询。
遍历,调用。

所以,订阅的基本单位是Store。

const listeners = (currentListeners = nextListeners)
for (let i = 0; i < listeners.length; i++) {
	const listener = listeners[i]
	listener()
}

6,返回该action
链式操作。

return action


这篇关于Redux源码分析——2,发出更新请求的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程