在React18中使用createRoot代替render
import * as ReactDOMClient from 'react-dom/client';
ReactDOMClient.createRoot(/*...*/);
ReactDOMClient.hydrateRoot(/*...*/);
什么是 root?
root就是指向React渲染dom树的一个最上层的数据结构。在旧的API中,root是不透明的,因为我们将它连接到DOM元素,并通过DOM节点访问它,从来不暴露给用户。
下面就是旧的API中,我们如何访问root元素,是使用dom直接访问。
import * as 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);
在新的API中,我们可以这么使用
import * as ReactDOMClient from 'react-dom/client';
import App from 'App';
const container = document.getElementById('app');
// Create a root.
const root = ReactDOMClient.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" />);
hydration该怎么办
修改之前
import * as ReactDOM from 'react-dom';
import App from 'App';
const container = document.getElementById('app');
// Render with hydration.
ReactDOM.hydrate(<App tab="home" />, container);
修改之后
import * as ReactDOMClient from 'react-dom/client';
import App from 'App';
const container = document.getElementById('app');
// Create *and* render a root with hydration.
const root = ReactDOMClient.hydrateRoot(container, <App tab="home" />);
// Unlike with createRoot, you don't need a separate root.render()
// call here
渲染回调函数应该怎么修改?
在旧的API中,我可以可以在组件渲染或更新后调用一个回调函数来处理什么。
import * as 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').
});
在新的API中,我们去掉了这个回调函数。
比如,我们在SSR中,并不期望出现这种回调函数的语法。为了避免这种歧义,这们推荐使用 requestIdleCallback, setTimeout 或是 ref的回调函数来代替以上。
旧的API的使用方式
import * as ReactDOMClient from 'react-dom/client';
function App() { return ( <div> <h1>Hello World</h1> </div> ); }
const rootElement = document.getElementById("root");
ReactDOMClient.render(<App />, rootElement, () => console.log("renderered"));
在新的API中,我们可以使用ref的回调函数来代替。
import * as ReactDOMClient from 'react-dom/client';
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 = ReactDOMClient.createRoot(rootElement);
root.render(<App callback={() => console.log("renderered")} />);