天天看点

定时器和promise_useState 在定时器和promise中的执行问题

定时器和promise_useState 在定时器和promise中的执行问题

为什么 setLoading 和 setSecond 在Promise和setimeout中执行会分别出发两次render,而直接调用的话只会触发一次render

注明: 这里去除useEffect执行前的首次渲染

效果如下

定时器和promise_useState 在定时器和promise中的执行问题

代码:function App() {

const ref = useRef(0)

const [loading, setLoading] = useState(true);

const [second, setSecond] = useState([]);

useEffect(() => {

console.log('useEffectuseEffectuseEffect')

setLoading(true)

Promise.resolve().then(() => {

console.log('Promise')

setLoading(false)

setSecond([1, 3, 4])

})

// setTimeout(() => {

// setLoading(false)

// setSecond([1, 3, 4])

// }, 1000)

// 执行setLoading和setSecond只执行一次渲染

// setLoading(false)

// setSecond([1, 3, 4])

}, []);

// console.log('mounted ----->', ++ref.current, second)

return (

{ (function() { console.log('render ----->', ref.current, second) })() }

{ loading && (function(){console.log('loading...')})() }

);

}