React中改变useState数值,无法立刻取到新值的问题
useState的set操作是异步的,不能立刻取到新值,如果想立刻取到新数值,只能额外再定义一个useRef变量作为副本,在进行set操作的同时更新useRef变量的数值,useRef变量.current可以立刻取到(使用useRef是因为函数组件内不应该使用var/let定义变量,异步操作获取var/let变量数值取到的永远都是最初默认值,例如在click事件中)
useState的两种set函数
const [useState,setUseState] = useState(0)
setUseState(1)
setUseState(PrevState =>[prevState + 1])//prevState是改变之前的state的值,return返回的值将坐位新的状态覆盖state的值
解决方法:
const [useState,setUseState] = useState(0)
const useStateRef = useRef(0)
const click = () => {
useStateRef.current = 1
setUseState(useStateRef.current)
console.log(useState)//旧数值
console.log(useStateRef.current)//打印新数值
}
看起来更好一点的代码方式:
const [useState,setUseState] = useState(0)
const useStateRef = useRef(0)
const click = () => {
setUseState((PrevState:number) =>{
useStateRef.current = 1