Skip to content

flushSync函数

flushSync类似Vue中的nextTick,用于页面渲染后指定执行一些逻辑。

1. 直接读取DOM元素问题

jsx
import { Row, Col, Button } from 'antd'
import { useState,useRef  } from 'react'

function App() {
  const [count, setCount] = useState(1)
  const ref = useRef(null)

  const handleClick = () => {
    setCount(count + 1)
    console.log(ref.current.innerHTML)
  }
  return (
    <>
      <Row>
        <Col span={24} ref={ref} >
          {count}
        </Col>
        <Col span={24}>
          <Button type='primary' onClick={handleClick}>点击</Button>
        </Col>
      </Row>
    </>
  )
}
export default App

Alt text

2. 使用flushSync

flushSync可以确保页面渲染后才往下执行:

jsx
import { Row, Col, Button } from 'antd'
import { useState, useRef } from 'react'
import { flushSync } from 'react-dom'

function App() {
  const [count, setCount] = useState(1)
  const ref = useRef(null)

  const handleClick = () => {
    flushSync(() => {
      setCount(count + 1)
    })
    // 拿DOM更新后的节点信息
    console.log(ref.current.innerHTML)
  }
  return (
    <>
      <Row>
        <Col span={24} ref={ref}>
          {count}
        </Col>
        <Col span={24}>
          <Button type="primary" onClick={handleClick}>点击</Button>
        </Col>
      </Row>
    </>
  )
}
export default App

运行效果:
Alt text