编程语言
首页 > 编程语言> > Redux源码分析——2,发出更新请求

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,请求,may,middleware,源码,Error,action,Redux,type
来源: https://blog.csdn.net/qq_37284843/article/details/123643787