【react】react18由render替换为createRoot区别
发布日期:2021-06-28 21:54:49 浏览次数:2 分类:技术文章

本文共 2092 字,大约阅读时间需要 6 分钟。

前言

  • 18版本由render替换为createRoot,看看有什么区别和为什么要这么做。

render与createRoot

  • react18中装载了2个api,所以你用以前的也没事。在源码中都有导入:
import {
findDOMNode, render, hydrate, unstable_renderSubtreeIntoContainer, unmountComponentAtNode,} from './ReactDOMLegacy';import {
createRoot, isValidContainer} from './ReactDOMRoot';
  • 名字很明显,一个叫legacy,在开发模式中,会提示你要换api了。

  • 老版本是这么使用render 的:

import ReactDOM from 'react-dom';import App from 'App';const container = document.getElementById('app');// Initial render.ReactDOM.render(
, container);// During an update, React would access// the root of the DOM element.ReactDOM.render(
, container);
  • 老版本渲染回调:
import ReactDOM from 'react-dom';import App from 'App';const container = document.getElementById('app');ReactDOM.render(container, 
, function() {
// Called after inital render or any update. console.log('rendered').});
  • 老版本注水:
import ReactDOM from 'react-dom';import App from 'App';const container = document.getElementById('app');// Render with hydration.ReactDOM.hydrate(
, container);
  • 新版本这么使用:
import ReactDOM from 'react-dom';import App from 'App';const container = document.getElementById('app');// Create a root.const root = ReactDOM.createRoot(container);// Initial render: Render an element to the root.root.render(
);// During an update, there's no need to pass the container again.root.render(
);
  • 新版本删除了渲染回调,因为回调触发在注水时可能与预期时间不一致。推荐使用idlecallback、settimeout或者ref,例如这么使用:
import ReactDOM from 'react-dom';function App({
callback }) {
// Callback will be called when the div is first created. return (

Hello World

);}const rootElement = document.getElementById("root");const root = ReactDOM.createRoot(rootElement);root.render(
console.log("renderered")} />);
  • 新版本注水:
import ReactDOM from ‘react-dom’;import App from 'App';const container = document.getElementById('app');// Create a root with hydration.const root = ReactDOM.createRoot(container, {
hydrate: true });root.render(
);
  • 可以看见新版本没有hydrate了。

  • 更换api的原因有2个,第一个就是为了把hydrate这个api换掉,然后做成一个配置项。第二个就是没必要把container传递给render,也就是说没必要存储container。

转载地址:https://blog.csdn.net/yehuozhili/article/details/117912552 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:【javascript】解决windows没有cp与rm命令
下一篇:【javascript】多入口构建优化记录终极版

发表评论

最新留言

感谢大佬
[***.8.128.20]2024年04月05日 19时09分50秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章