useState Hooks 原理

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
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值