React useState Hooks 原理
import React, {
useState,
} from "react";
import ReactDOM from 'react-dom';
let _state: any = [];
let index: any = 0;
// 手写useState
const myUseState = (initialValue: any) => {
const currentIndex = index;
// 如果_state[currentIndex]个是空的那么_state[index]就等于_state[initialValue]
_state[currentIndex] =
_state[currentIndex] === undefined ? initialValue : _state[currentIndex];
// 修改 useState方法
// bug 修改的方法不能传函数
const setState = (newValue: any) => {
_state[currentIndex] = newValue;
render();//更新页面
};
// 如果有多个 useState用一个数组存
index += 1
return [_state[currentIndex], setState]
};
const render = () => {
// 初始化index
index = 0;
ReactDOM.render(<App />, document.getElementById('root'));
}
function App() {
// 返回一个 [_state[currentIndex], setState] 一个初始值一个 修改的方法
const [n, setN] = myUseState(0)
// 功能和下面一样
//const [n, setN] = useState(0)
// let m: any, setm: (arg0: any) => void;
// if (n % 2 === 1) {
// [m, setm] = useState(0)
// }
return <div className="sss">
<div>{n}</div>
<button onClick={() => setN(n + 1)}>+1按钮</button>
{/* <div>{m}</div>
<button onClick={() => setm(m + 1)}>+1按钮</button> */}
</div>;
}
ReactDOM.render(<App />, document.getElementById('root'));
当然正真 useState 没有那么简单
注意
useState
使用状态
const [n,setN]=React.useState(0)
const [user,setUser]=React.useState({name;“F”})
注意事项
1.不可以局部更新
如果state是个对象能不能 部分setState
答案是不行的
应为set不会帮我吗合并属性
useReducer 会合并属性吗 也不会
react需要你自己合并属性
2.useState 调用顺序要注意
否则会出BUG