React中如何避免状态未变更时触发组件重渲染?
React 避免无意义重渲染的其他方案
当调用setState传入与当前状态完全相同的值时,类组件默认仍会触发重渲染。除了你提到的shouldComponentUpdate()和PureComponent,还有以下几种实现方式:
1. 手动判断状态再调用 setState
在更新状态前先对比新旧值,只有当值确实变化时才执行setState,从源头避免不必要的更新触发。修改你的示例代码如下:
class App extends Component { constructor() { super(); this.state = { value: "abcd" }; } handlePress = () => { // 先判断状态是否变化,再决定是否更新 if (this.state.value !== "abcd") { this.setState({ value: "abcd" }); } }; render() { console.log("render"); return ( <div> <h1>{this.state.value}</h1> <button onClick={this.handlePress}>Press</button> </div> ); } }
2. 使用 React.memo(函数组件场景)
如果将组件迁移为函数组件,React.memo是专门用于避免无意义重渲染的工具。它会对组件接收的props进行浅比较,若props未发生变化则跳过组件重渲染。示例:
import React, { useState } from 'react'; // 用 React.memo 包裹组件 const App = React.memo(() => { const [value, setValue] = useState("abcd"); const handlePress = () => { setValue("abcd"); }; console.log("render"); return ( <div> <h1>{value}</h1> <button onClick={handlePress}>Press</button> </div> ); });
补充说明
类组件中并没有其他专门用于控制重渲染的生命周期方法,PureComponent本质就是内置了浅比较逻辑的shouldComponentUpdate,而手动判断状态或迁移为函数组件使用React.memo是更灵活的替代方案。
内容的提问来源于stack exchange,提问作者De-J
相关产品推荐
相关产品推荐

