函数组件中React.memo与Context配合使用
- 创建Context
import React from 'react';
const MyContext = React.createContext();
- 使用React.memo包裹函数组件
const MyFunctionComponent = React.memo(({ value }) => {
return <div>{value}</div>;
});
- 在函数组件中消费Context
const FunctionComponentWithContext = () => {
const contextValue = React.useContext(MyContext);
return <MyFunctionComponent value={contextValue} />;
};
- 示例完整代码
import React from'react';
const MyContext = React.createContext();
const MyFunctionComponent = React.memo(({ value }) => {
return <div>{value}</div>;
});
const FunctionComponentWithContext = () => {
const contextValue = React.useContext(MyContext);
return <MyFunctionComponent value={contextValue} />;
};
const App = () => {
const contextData = 'Hello, Context!';
return (
<MyContext.Provider value={contextData}>
<FunctionComponentWithContext />
</MyContext.Provider>
);
};
export default App;
类组件中React.memo与Context配合使用
- 创建Context
import React from'react';
const MyContext = React.createContext();
- 类组件继承React.Component
class MyClassComponent extends React.Component {
render() {
return <div>{this.props.value}</div>;
}
}
- 使用React.memo包裹类组件
const MemoizedClassComponent = React.memo(MyClassComponent);
- 在类组件中消费Context
class ClassComponentWithContext extends React.Component {
static contextType = MyContext;
render() {
const contextValue = this.context;
return <MemoizedClassComponent value={contextValue} />;
}
}
- 示例完整代码
import React from'react';
const MyContext = React.createContext();
class MyClassComponent extends React.Component {
render() {
return <div>{this.props.value}</div>;
}
}
const MemoizedClassComponent = React.memo(MyClassComponent);
class ClassComponentWithContext extends React.Component {
static contextType = MyContext;
render() {
const contextValue = this.context;
return <MemoizedClassComponent value={contextValue} />;
}
}
const App = () => {
const contextData = 'Hello, Context!';
return (
<MyContext.Provider value={contextData}>
<ClassComponentWithContext />
</MyContext.Provider>
);
};
export default App;
注意要点
- Context值变化:React.memo默认只进行浅比较,若Context中的值是对象或数组,当对象或数组内部数据变化但引用不变时,React.memo包裹的组件不会重新渲染。可通过自定义比较函数(
React.memo(Component, compareFunction)
)来处理这种情况,在比较函数中进行深比较。
- 性能开销:虽然React.memo可避免不必要渲染,但深比较等复杂操作本身也有性能开销,需权衡是否值得。
- 组件层级:若Context值在较高层级频繁变化,可能导致过多组件不必要渲染,可考虑拆分Context或使用
useReducer
结合Context来优化,让Context值变化更可控。