React Hook中useState更新延迟问题

例如下面的代码 

const [currentIndex, setCurrentIndex] = useState(0)
  const handleLeft = () => {
     setCurrentIndex(currentIndex+ 1)
     console.log(currentIndex)
  }

初始化currentIndex为0 每次执行handleLeft函数是让currentIndex加1, 之后立即获取currentIndex的值发现 第一次执行currentIndex = 0

第二次执行currentIndex = 1 每次都跟实际情况差一个  查阅资料发现useState必须要执行完react整个生命周期才会获取最新值

解决方案: 用useRef代替

 const currentIndexRef = useRef(0); // 不能用useState 会导致数据更新不及时
  const handleLeft = () => {
     currentIndexRef.current += 1
     console.log(currentIndexRef.current)
  }

 

 

你可能感兴趣的:(react)