每一次渲染都有它自己的props和state
const State = () => {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>)
}
每一次渲染都有自己的事件处理函数
const State = () => {
const [count, setCount] = useState(0);
const showCount = () => {
setTimeout(() => {
alert(count)
}, 3000)
}
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
<button onClick={showCount}>
show Count
</button>
</div>)
}
每次渲染时候都会有一个“新版本的”showCount
函数,每一个版本的showCount
都会记住自己的count
任意一次的渲染中,props和state始终保持不变。props和state在不同的渲染中相互独立。事件处理函数也是独立的,它们都属于特定的一次渲染。
每次渲染都有它的Effects
effects其实并没有两样, 每次渲染都会有自己的Effects
const State = () => {
const [count, setCount] = useState(0);
useEffect(() => {
setTimeout(() => {
console.log(`you cliced ${count} times`)
}, 3000)
})
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>)
}