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

reselect 源码解读 #26

Open
negativeentropy9 opened this issue Sep 18, 2019 · 0 comments
Open

reselect 源码解读 #26

negativeentropy9 opened this issue Sep 18, 2019 · 0 comments

Comments

@negativeentropy9
Copy link
Owner

reselect 源码解读

Selectors can compute derived data, allowing Redux to store the minimal possible state.

Selectors are efficient. A selector is not recomputed unless one of its arguments changes.

Selectors are composable. They can be used as input to other selectors.

源代码

源码比较短,加注释才100多行。

核心 api

createSelector

该函数执行返回结果是一个记忆函数,结合 redux 使用时,一般调用生成的 selector 函数的参数是 store。若 store 发生变化,会根据 dependency 值 来重新计算传入 createSelector 的 transform 函数返回值;若 store 不发生变化,直接返回上一个缓存的结果值。

相关工具 api

默认比较函数

function defaultEqualityCheck(a, b) {
  return a === b
}

默认记忆函数

export function defaultMemoize(func, equalityCheck = defaultEqualityCheck) {
  let lastArgs = null
  let lastResult = null
  // we reference arguments instead of spreading them for performance reasons
  return function () {
    if (!areArgumentsShallowlyEqual(equalityCheck, lastArgs, arguments)) {
      // apply arguments instead of spreading for performance.
      lastResult = func.apply(null, arguments)
    }

    lastArgs = arguments
    return lastResult
  }
}

可定制比较函数和记忆函数,参考

codesandbox demo

注意事项

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

No branches or pull requests

1 participant