前言
关于react hooks的useState,在写hooks的时候经常用到,我在之前也有文章写过reactHooks中useState的使用小结 关于useState这个hooks,我们如何手写实现呢?
useState使用小结
1、接收任意类型的入参数,可以是数组、对象、函数等。
2、可以被多次调用,每调用一次都可以解构出不同的状态变量。
3、setState 也可以传入回调函数。改回调函数会被自动传入当前对应的状态变量。
4、被结构出来的状态变量和更改状态变量的方法是1对1绑定的。
5、调用setState后,要重新render函数组件
使用useState的案例
import React, { useState } from "react";
export default function App() {
// 声明一个新的叫做 “count” 的 state 变量
const [count, setCount] = useState([0]);
const [name, setName] = useState("haorooms");
const [haorooms, setHaorooms] = useState(() => "欢迎haorooms");
return (
<div>
<p>
You clicked {count}
{count[0]} times
</p>
<p>Call me {name}</p>
<p>{name} is haorooms blog ?</p>
<p>{haorooms} is good blog ?</p>
<button
onClick={() => {
setCount([count[0] + 1]);
setName("haorooms博客");
setHaorooms((preRooms) => `欢迎${preRooms}`);
}}
>
点击
</button>
</div>
);
}
手写react hooks的useState
import ReactDOM from "react-dom";
let state = [];
let setters = [];
let stateIndex = 0;
const getStateByFn = (v, params) => {
if (typeof v === "function") {
const _newState = v(params);
if (!_newState) throw "You must be return state";
return _newState;
}
return v;
};
function createSetter(index) {
return function (newState) {
state[index] = getStateByFn(newState, state[index]);
render();
};
}
function useState(initialState) {
state[stateIndex] = state[stateIndex]
? getStateByFn(state[stateIndex])
: getStateByFn(initialState);
setters.push(createSetter(stateIndex));
let value = state[stateIndex];
let setter = setters[stateIndex];
stateIndex++;
return [value, setter];
}
function render() {
stateIndex = 0;
ReactDOM.render(<App />, document.getElementById("root"));
}
export default function App() {
// 声明一个新的叫做 “count” 的 state 变量
const [count, setCount] = useState([0]);
const [name, setName] = useState("haorooms");
const [haorooms, setHaorooms] = useState(() => "欢迎haorooms");
return (
<div>
<p>
You clicked {count}
{count[0]} times
</p>
<p>Call me {name}</p>
<p>{name} is haorooms blog ?</p>
<p>{haorooms} is good blog ?</p>
<button
onClick={() => {
setCount([count[0] + 1]);
setName("haorooms博客");
setHaorooms((preRooms) => `欢迎${preRooms}`);
}}
>
点击
</button>
</div>
);
}
上面代码直接copy出来,作为app.js 直接引入既可以测试了!