问题:
在hooks中,修改状态的是通过useState返回的修改函数实现的.它的功能类似于class组件中的this.setState().而且,这两种方式都是异步的.可是this.setState()是有回调函数的,那useState()呢?
问题点:
- 它异步且没有回调函数
const [count,setCount] = useState(1)
useEffect(()=> {
setCount(2,()=>{
console.log('测试hooks的回调');
})
console.log(count);
},[])
可以看到提示 “State updates from the useState() and useReducer() Hooks don’t support the second callback argument. To execute a side effect after rendering, declare it in the component body with useEffect().”是不支持回调函数的形式的。因为setCount是异步的,所以打印count是在改变count之前的。
如果我们想要在打印的时候就拿到最新的值,那么我们可以通过setCount的第二个参数指定依赖项
const [count,setCount] = useState(1)
useEffect(()=> {
setCount(2)
console.log(count);
},[count])
当count发生变化的时候,useEffect就会再次相应,但是这样就会有个问题,当count从1变为2的时候useEffect的回调函数会再次执行,就会分别打印1,2两次。
useEffect(()=> {
let currentValue = null
setCount((preVal)=>{
currentValue=preVal
return 2
})
if(currentValue!==count){
console.log(count);
}
},[count])
通过添加判断条件,我们可以让想要执行的代码只执行一次