美文网首页Web 前端开发 程序员
十行代码实现React Hooks

十行代码实现React Hooks

作者: 济丰 | 来源:发表于2019-03-13 22:07 被阅读0次

    本文转自我的博客十行代码实现React Hooks

    代码解千言

    export const React = (function() {
      const hooks = [];
    
      let currentHook = 0;
      return {
        render(Component) {
          const App = Component();
          // run effects
          App.render();
          currentHook = 0;
          // reset for next render
          return App;
        },
        /**
         * similar to https://reactjs.org/docs/hooks-reference.html#conditionally-firing-an-effect
         * @param {*} callback
         * @param {*} depArray
         */
        useEffect(callback, depArray) {
          const hasNoDeps = !depArray;
          let deps = hooks[currentHook]; // type: array | undefined
          const hasChangedDeps = deps
            ? !depArray.every((el, i) => el === deps[i])
            : true;
          if (hasNoDeps || hasChangedDeps) {
            callback();
            deps = depArray;
          }
          currentHook++; // done with this hook
        },
        /**
         * similar to https://reactjs.org/docs/hooks-state.html
         * @param {*} init
         */
        useState(init) {
          hooks[currentHook] = hooks[currentHook] || init; // type: any
          const setStateHookIndex = currentHook; // for setState's closure!
          const setState = newState => (hooks[setStateHookIndex] = newState);
          return [hooks[currentHook++], setState];
        }
      };
    })();
    

    “魔法”就是数组。

    相关文章

      网友评论

        本文标题:十行代码实现React Hooks

        本文链接:https://www.haomeiwen.com/subject/cqmxmqtx.html