React18 新特性一览
升级: React 18 相较于之前的React 版本来说 主要有以下几个方面的升级:
1 增加了一些新的API
2 底层逻辑的优化
3 React Current Mode 并发模式的实现
4 同时需要注意的是React 18 不支持IE浏览器。
5 新增了一部分hooks以及服务端渲染的API
a: 根节点改变挂载方式
使用createRoot 实现原有的render 方式的挂载 。
eg: before
1 import * as ReactDOM from 'react-dom'; 2 import App from 'App'; 3 4 const container = document.getElementById('app'); 5 6 // Initial render. 7 ReactDOM.render(container,<App tab="home" />); 8 9 // During an update, React would access 10 // the root of the DOM element. 11 ReactDOM.render(container,<App tab="profile" />);
after: 在新的React18 版本当中使用createRoot 来创建一个根节点 root, 然后使用其 render 方法完成渲染。
1 import * as ReactDOM from 'react-dom'; 2 import App from 'App'; 3 4 const container = document.getElementById('app'); 5 6 // Create a root. 7 const root = ReactDOM.createRoot(container); 8 9 // Initial render: Render an element to the root. 10 root.render(<App tab="home" />); 11 12 // During an update, there's no need to pass the container again. 13 root.render(<App tab="profile" />);
tips: 使用render 方法时 React应用的根节点对于使用者来说是不透明的,我们无法取到这个值,同时使用createRoot方法时 我们可以自定义我们的根节点 这样的话 只需要调用root的render方法即可。有利于后续Current Mode 模式的渲染。