【react】react18由render替换为createRoot区别

前言

  • 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(<App tab="home" />, container);

// During an update, React would access
// the root of the DOM element.
ReactDOM.render(<App tab="profile" />, container);
  • 老版本渲染回调:
import ReactDOM from 'react-dom';
import App from 'App';

const container = document.getElementById('app');

ReactDOM.render(container, <App tab="home" />, 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(<App tab="home" />, 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(<App tab="home" />);

// During an update, there's no need to pass the container again.
root.render(<App tab="profile" />);

  • 新版本删除了渲染回调,因为回调触发在注水时可能与预期时间不一致。推荐使用idlecallback、settimeout或者ref,例如这么使用:
import ReactDOM from 'react-dom';

function App({ callback }) {
  // Callback will be called when the div is first created.
  return (
    <div ref={callback}>
      <h1>Hello World</h1>
    </div>
  );
}

const rootElement = document.getElementById("root");

const root = ReactDOM.createRoot(rootElement);
root.render(<App callback={() => 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(<App tab="home" />);

  • 可以看见新版本没有hydrate了。

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

  • 5
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

业火之理

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值