模拟React hooks之useRef

95 阅读1分钟

模拟React.useRef

const React = {
  // 用来存state历史值
  hookState: [],
  // 每个state对应的下标
  stateIndex: 0,
  useRef(initialValue) {
    // 声明要返回的state
    let state;
    if (this.hookState[this.stateIndex]) {
      // 如果存在历史值,就取值
      state = this.hookState[this.stateIndex]
    } else {
      // 没有历史值,就把 initialValue 赋值给state, 并记录历史值(this.hookState[this.stateIndex])
      state = this.hookState[this.stateIndex] = { current: initialValue ? initialValue : null }
    };
    // stateIndex下标累加,用于记录下个state(food)
    this.stateIndex++;
    return state;
  },
}

定义一个 functionComponent 模拟函数式组件

function functionComponent() {
  const person = React.useRef({ name: 'czh' });
  const food = React.useRef('apple');
  return {
    person,
    food
  }
};

定义一个组件实例

var instance = functionComponent();
console.log('instance', JSON.stringify(instance));
// {"person":{"current":{"name":"czh"}},"food":{"current":"apple"}}
setTimeout(() => {
  instance.person.current = { name: 'lzw' };
  console.log('instance', JSON.stringify(instance));
  // {"person":{"current":{"name":"lzw"}},"food":{"current":"apple"}}
}, 3000);