react hooks useState闭包理解

 const [ count, setCount ] = useState( 0 )
  console.log( 'redner...' );
  const cuRef = useRef( {
    timer: null,
    count: 0
  } )
  const printBtnClick = () => {
    cuRef.current.count = count + 1
    console.log( 'printBtnClick 1', count );
    setCount( count + 1 )
    console.log( 'printBtnClick 2', count );
    // if ( cuRef?.current?.timer ) {
    //   clearTimeout( cuRef.current.timer )
    // }
    // cuRef.current.timer = setTimeout( () => {
    //   console.log( 'printBtnClick 3', count, cuRef.current );
    // }, 5000 );
    setTimeout( () => {
      console.log( 'printBtnClick 3', count, cuRef.current );
    }, 5000 );
    //  btnClick && btnClick()
  }

react hooks useState闭包理解

react hooks 每个状态都会形成一个闭包环境,  如果想让多个闭包之前共享变量,可以用单例模式或者useRef传值方式

上一篇:vue ele table表格 设置只能勾选一个


下一篇:mysql常用函数