- 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>
)
}