- useState 的基本用法
- useState 的基本问题
- 手写 useState
1. useState 的基本用法
== 注意: useState 不能写在 If 里,因为会导致_state 中的下标无法一一对应新的属性 key==
function App (){
const [n,setN] = React.useState(0);
const add = ()=>{
setN(n+1)
}
return (
<div>
<p>{n}</p>
<button onClick="add">add</button>
</div>
)
}
2. useState 的基本问题
- 执行 setN 的时候会发什么吗?n 会不会变化?app () 会重新执行吗?答: 首先每个组件有自己的数据 x,当 setN 执行时一会更新 x 的值,此时的 n 会发生变化但不会渲染到 ui 中,只有更新 app()才会更新 UI,所以每次中 setN,app () 会被重新渲染.
- 如果 app () 会被重新渲染,setState (0) 的时候。每次 n 的值会不会不同。答: 当重新被渲染时,n 己经被 x 赋值,所以 setState (0) 已经被 x 的值替换掉,n 的值会不同
3. 实现 useState 的思路
import React,{useState} from "react"
const _state = [];
let index = 0;
const myuseState = (value)=>{
let blockIndex = index;
_state[blockIndex] = _state[blockIndex]===nudefined?value:_state[blockIndex]
const setState = (newValue)=>{
_state[blockIndex] = newValue;
render()
}
index++
return [_state,setState]
}
const render(){
ReactDOM.render(<App />,document.getElementById("root"));
}
function App(){
const [n,setN] = useState(0);
const [m,setM] = useState(0)
const add = ()=>{
setN(n+1)
}
const addM = ()=>{
setM(m+1)
}
return (
<div>
<p>
{n}
<button onClick={add}>add</button>
</p>
<p>
{m}
<button onClick={addM}>addM</button>
</p>
</div>
)
}