【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。

你可能感兴趣的:(React)