脚本宝典收集整理的这篇文章主要介绍了[Reac] React 18,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
ReactDOM.createRoot(document.getElementById("root")).render(<App />);
Behavior of each type of API for React 17 and 18:
let root1 = document.getElementById("root"); let root2 = document.getElementById("root-2"); ReactDOM.createRoot(root1).render(<App root="18" />); ReactDOM.render(<App root="17" />, root2)
React's legacy root API (render
) took a callback function. React called this function once the post-render. With new streaming capabilities scheduled for React 18, this feature becomes unpredictable. Replace it with a ref callback — or one of these other strategies.
There are several ways to fix the previous warning. First one is by using useEffect
function App() { React.useEffect(() => console.log("React rendered"), []) return <div> Hello, React! </div> }
we can also use callback
function:
ReactDOM.createRoot(root).render( <App callback={(ref) => console.log(ref.tagName)} /> ); function App({ callback }) { return <div ref={callback}> Hello, React! </div> }
const REACT_18 = true; if (REACT_18) { ReactDOM.createRoot(root).render(<App />); } else { ReactDOM.render(<App />, root); }
In previous versions of React, state update batching only happened inside of event handlers. In React 18, all updates are batched, regardless of when or where they are called. Opt into automatic batching with createRoot
.
function App() { let [count, updateCount] = React.useState(1); let [isOdd, updateIsOdd] = React.useState(true); function handleClick() { setTimeout(() => { updateCount((count) => count + 1); updateIsOdd((oddness) => !oddness); }, 0); } console.count("re-rendered"); return ( <div> <button type="button" onClick={handleClick}> {count} {isOdd.toString()} </button> </div> ); }
In v17, each time button was clicked, will console log two times. This is because we call the update function in setTimeout.
If we did following, then it only log once
function handleClick() { updateCount((count) => count + 1); updateIsOdd((oddness) => !oddness); }
But in v18 the problem was solved.
React 17 exposes an undocumented API named unstable_batchedUpdates
. It batches multiple useState update calls — inside of asynchronous callbacks — and reduces extraneous renders.
In React 18, all useState
updates are batched, making unstable_batchedUpdates
inert. Remove all uses of unstable_batchedUpdates
.
In React 18, useState update calls are batched for improved performance. A new API — ReactDOM.flushSync
— lets us selectively escape batching. This option is useful when reading the DOM after state changes. Use ReactDOM.flushSync
to exempt specific state updates from batching.
ReactDOM.flushSync(() => { updateCount((count) => count + 1) }); updateIsOdd((oddness) =>!oddness)
以上是脚本宝典为你收集整理的[Reac] React 18全部内容,希望文章能够帮你解决[Reac] React 18所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。