/*
为什么hooks不能写在条件语句和循环中?
因为写在条件语句和循环可能会导致hooks的执行顺序发生改变,因为react hooks内部是通过,hooks的调用顺序来记录对应的状态;
比如第一次调用useState第二次调用useState,那么react是怎么知道对应的是哪个状态呢?就是通过hooks链表的固定顺序来确定对应哪个状态的;
*/
import React from ‘react’
const render = () => {
// 重置hookIndex
hookIndex = 0;
ReactDOM.render(, document.querySelector(‘#root’));
}
let hookIndex = 0;
let hookState = [];
const myUseState = (initState) => {
// 每次调用myUseState对应的索引,利用闭包来去确定要set的状态值在链表中对应的索引
let currentHookIndex = hookIndex;
// 创建一个变量,来存储初始状态,
let state = hookState[currentHookIndex] || initState;
// 更新状态的函数
const setState = (newState) => {
hookState[currentHookIndex] = newState;
// 此处调用render函数重新渲染我们的组件
render();
};
hookIndex++;
return [state, setState];
}
const App = () => {
const [a, setA] = myUseState(0);
const [b, setB] = myUseState(1);//如果这个hooks被条件语句包裹那么下一个myUseState拿到的currentHookIndex就是上一个的currentHookIndex这样set的时候状态就不对应
const [c, setC] = myUseState(2);
}