2022-05-21 React18 異步渲染

import React, { useCallback, useState } from 'react';
import SendButton from './SendButton';

export default function AsyncHook() {
  const [a, setA] = useState(0);
  const async = () => {
    setTimeout(() => {
      setA((c) => c + 1);
      window.console.log(a);
      setA((c) => c + 1);
      window.console.log(a);
      setA((c) => c + 1);
      window.console.log(a);
      // react17: 結(jié)果加3, renderTime 3次
    }, 0);
  };

  const async2 = () => {
    setTimeout(() => {
      setA(a + 1);
      window.console.log(a);
      setA(a + 1);
      window.console.log(a);
      setA(a + 1);
      window.console.log(a);
    }, 0);

    // react17: 結(jié)果+1, renderTime 調(diào)用2次
  };

  const sync = () => {
    setA((c) => c + 1);
    window.console.log(a);
    setA((c) => c + 1);
    window.console.log(a);
    setA((c) => c + 1);
    window.console.log(a);
    // react17: 結(jié)果+3, renderTime 調(diào)用1次
  };

  const sync2 = () => {
    setA(a + 1);
    window.console.log(a);
    setA(a + 1);
    window.console.log(a);
    setA(a + 1);
    window.console.log(a);
    // react17: 結(jié)果+1, render time調(diào)用一次
    // React18: 結(jié)果+1, render time調(diào)用一次 (上述幾個demo表現(xiàn)與這個一致)
  };

  window.console.log('render times', a);

  const [text, setText] = useState('');

  const onClick = useCallback(() => {
    window.console.log('send: ', text);
  }, []);

  const onTextChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setText(e.target.value);
  };

  return (
    <div>
      <div>{a}</div>
      <button onClick={async} className="bg-teal-300">
        async
      </button>
      <button onClick={async2} className="bg-teal-300">
        async2
      </button>
      <button onClick={sync}>sync</button>
      <button onClick={sync2}>sync2</button>
      <hr />
      <input type="text" onChange={onTextChange} />
      <SendButton onSendMessage={onClick} />
    </div>
  );
}
/** 在React17中結(jié)果是一致的
 * 異步async render times會調(diào)用三次 結(jié)果+3
 * 異步async2 render times會調(diào)用2次, 結(jié)果加1

 * 同步: render times只調(diào)用一次, 結(jié)果+3
 * 同步: render times只調(diào)用一次, sync2 結(jié)果+1
 *
 * 結(jié)果都是增加三次
 *
 * react18中,
 * 異步 render times會調(diào)用一次
 * 同步: render times只調(diào)用一次
 * 行為保持了一致
 */
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容