React性能优化--未必memo
React-性能优化(不用memo)Round One 状态下沉Round Two 内容提升
React-性能优化(不用memo)
相信大家在使用React时,经常会遇到页面出现重复渲染的情况,有时候,可能渲染的数据不多,从视觉上感觉不到性能的消耗,但是有时候却很尴尬,比如渲染一个可编辑的列表,当列表的行数稍微有点的多的时候,你随便在页面上面更新一下跟列表无关的state,都有可能会导致卡顿一会,这就是页面在渲染的同时,导致列表也重新渲染了,but,我压根就不想它这时候渲染啊?肿么办?
如果熟悉hooks,这时候第一想到的应该是useMemo,没错,套上它,虽然超薄,防护却是杠杠的,只是是不是每次都得套上useMemo才觉得安全呢?这也未必,先去取个经再说,oh no,是取个女儿国国王再说!
import React, { useState } from "react";const ExpensiveComponent = () => { let now = performance.now(); while (performance.now() - now < 100) { // 这是G点,就是需要关注的点!容易乱动的地方 console.log(performance.now()); } return <p>这是一个让人崩溃的组件</p>;};const PerformanceOptimizationsComponent = () => { const [color, setColor] = useState("blue"); return ( <div> <div style={{color}}>my color</div> <input type="text" value={color} onChange={(e) => { setColor(e.target.value) }}/> <ExpensiveComponent/> </div> );};
Round One 状态下沉
所谓状态下沉,就是把需要更新的状态,下沉到独立的子组件中,这样的话,子组件的状态变更,不会影响到兄弟组件,更不会影响到父组件,既然你不老实,就拔出来,给你套上金刚罩,看你还敢不敢三心二意了。废话不多,上活。
更改后import React, { useState } from "react";const Form = () => { const [color, setColor] = useState("blue"); return ( <> <div style={{ color }}>my color</div> <input type="text" value={color} onChange={(e) => { setColor(e.target.value); }}/> </> );};const ExpensiveComponent = () => { let now = performance.now(); while (performance.now() - now < 100) { // G点不到,就淡定了。 console.log(performance.now()); } return <p>这是一个让人崩溃的组件</p>;};const PerformanceOptimizationsComponent = () => { return ( <div> <Form/> <ExpensiveComponent/> </div> );};export default PerformanceOptimizationsComponent;
Round Two 内容提升
当一部分state在高开销树的上层代码中使用时上述解法就无法奏效了。举个栗子,如果我们将color放到父元素div中。
----:靠,这比新冠变异变的还快,放开还是管控?
import React, { useState } from "react";const ExpensiveComponent = () => { let now = performance.now(); while (performance.now() - now < 100) { // 直接举手投降 console.log(performance.now()); } return <p>这是一个让人崩溃的组件</p>;};const PerformanceOptimizationsComponent = () => { const [color, setColor] = useState("blue"); return ( <div style={{color}}> <div>my color</div> <input type="text" value={color} onChange={(e) => { setColor(e.target.value) }}/> <ExpensiveComponent/> </div> );};export default PerformanceOptimizationsComponent;
last 修改后 import React, { useState } from "react";const ExpensiveTree = () => { let now = performance.now(); while (performance.now() - now < 100) { // 再来一次! console.log(performance.now()); } return <p>放过我吧!~</p>;};const Last = ({ children }) => { const [color, setColor] = useState("blue"); return ( <div style={{ color }}> <div>my color</div> <input type="text" value={color} onChange={(e) => { setColor(e.target.value); }}/> {children} </div> );};const PerformanceOptimizationsComponent = () => { return ( <Last> <ExpensiveTree/> </Last> );};export default PerformanceOptimizationsComponent;
貌似没用上memo,也解决了这些令人蛋疼的事情!~