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

重温 React hook 基本原理 #326

Open
xxleyi opened this issue Nov 7, 2021 · 0 comments
Open

重温 React hook 基本原理 #326

xxleyi opened this issue Nov 7, 2021 · 0 comments
Labels

Comments

@xxleyi
Copy link
Owner

xxleyi commented Nov 7, 2021

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);
@xxleyi xxleyi added the HOW label Nov 7, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant