前言
Hook出现之前我们对比Function components和 class components之间差异性,一般会对比:
- 渲染性能
- 纯的组件
hooks出现之后,我们可以得出他们最大的差异性:
函数组件能够捕获渲染的值
也就是所谓的capture value
示例
函数组件:
const Capture = () => {
const [count, setCount] = useState(0);
const handlerChange = (e) => {
setCount(e.target.value)
}
const handlerClick = () => {
setTimeout(() => {
alert(count)
}, 3000)
}
return (
<div>
<button onClick={handlerClick}>get count</button>
<input onChange={handlerChange}></input>
</div>
)
}
export default Capture;
我们可以看到三秒之后获取的还是之前输入的值
class组件
class Claz extends React.Component {
constructor(props) {
super(props)
this.state = {
count: 0
}
}
handlerChange = (e) => {
this.setState({
count: e.target.value
})
}
handlerClick = () => {
setTimeout(() => {
alert(this.state.count)
}, 3000)
}
render() {
return (
<div>
<button onClick={this.handlerClick}>get count</button>
<input onChange={this.handlerChange}></input>
</div>
)
}
}
hook如何避免capture value的问题
答案是
useRef
const Capture = () => {
const [count, setCount] = useState(0);
const latestCount = useRef(0);
const handlerChange = (e) => {
latestCount.current = e.target.value;
setCount(e.target.value)
}
const handlerClick = () => {
setTimeout(() => {
alert(latestCount.current)
}, 3000)
}
return (
<div>
<button onClick={handlerClick}>get count</button>
<input onChange={handlerChange}></input>
</div>
)
}
使用useRef手动的来跟踪变化,其实我们有更好的方式来自动追踪变化
const Capture = () => {
const [count, setCount] = useState(0);
const latestCount = useRef(0);
const handlerChange = (e) => {
setCount(e.target.value)
}
useEffect(() => {
latestCount.current = count;
}, [count])
const handlerClick = () => {
setTimeout(() => {
alert(latestCount.current)
}, 3000)
}
return (
<div>
<button onClick={handlerClick}>get count</button>
<input onChange={handlerChange}></input>
</div>
)
}