巧妙的hooks, useState

·  阅读 811
巧妙的hooks, useState
hooks创建及控制执行

let execution = null;
let current = null;
let context = null;
let args = null;


const hooked = callback => {

  const details = {i: 0, stack: []};

  return function hook() {
    details.i = 0;
    execution = details;
    current = hook;
    context = this;
    args = arguments;
    return callback.apply(context, args);
  };
};

const useState = value => {
  const hook = current;
  const ctx = context;
  const rest = args;
  const {i, stack} = execution;
  execution.i++;

  if (i === stack.length) {
    stack.push(value);
  }

  return [
    stack[i],
    value => {
      stack[i] = value;
      hook.apply(ctx, rest);
    }
  ];
};

复制代码
举一个小例子🌰
const toBeWrapped = start => {
  const [num, update] = useState(start);
  console.log(`Counting: ${num}`);
  setTimeout(update, 1000, num + 1);
};

function Counter() {
  return hooked(toBeWrapped).apply(this, arguments);
}

Counter(0);

复制代码
一起玩转React
分类:
前端
标签:
分类:
前端
标签:
收藏成功!
已添加到「」, 点击更改