xxleyi / learning_list

聚集自己的学习笔记
11 stars 3 forks source link

重温 React hook 基本原理 #326

Open xxleyi opened 2 years ago

xxleyi commented 2 years ago
const log = console.log;

// closure: function has private state
const SimpleReact = (function () {
  let stateList = [];
  let index = 0;
  function useState(initialVal) {
    // hook 在不同 render 之间,必须以一个固定顺序执行
    let currentStateIndex = index++;
    let currentState = stateList[currentStateIndex] || initialVal;
    return [
      currentState,
      (val) => {
        stateList[currentStateIndex] = val;
      }
    ];
  }
  function render(Component) {
    // 每次 render 时,从头开始遍历 stateList
    index = 0;
    return Component();
  }
  return { useState, render };
})();

function Component() {
  const [count, setCount] = SimpleReact.useState(0);
  const [input, setInput] = SimpleReact.useState("");
  log({ count, input });
  const click = () => setCount(count + 1);
  const type = (text) => setInput(text);
  return {
    effect: (callback) => {
      callback({ click, type });
    }
  };
}

// 单纯渲染
SimpleReact.render(Component);
// 渲染之后,执行点击动作
SimpleReact.render(Component).effect(({ click }) => {
  click();
});
// 渲染之后,执行输入动作
SimpleReact.render(Component).effect(({ type }) => {
  type("test");
});
// 渲染之后执行点击和输入动作
SimpleReact.render(Component).effect(({ click, type }) => {
  click();
  type("apple");
});
// 单纯渲染
SimpleReact.render(Component);
// 单纯渲染
SimpleReact.render(Component);