面试题答案
一键面试1. 性能优化方面
- 避免不必要的重渲染:高阶组件可能会导致组件不必要的重渲染。可以使用
React.memo
包裹被高阶组件增强的组件,仅当组件的 props 发生变化时才重新渲染。例如:
import React from'react';
// 普通组件
const MyComponent = ({ data }) => {
return <div>{data}</div>;
};
// 使用 React.memo 包裹
const MemoizedMyComponent = React.memo(MyComponent);
// 高阶组件示例
const withLogging = (WrappedComponent) => {
return (props) => {
console.log('Component rendered');
return <WrappedComponent {...props} />;
};
};
// 组合高阶组件和 React.memo 组件
const EnhancedComponent = withLogging(MemoizedMyComponent);
- 合并高阶组件:减少高阶组件的嵌套层数,将多个功能相似的高阶组件合并成一个。例如,假设有权限控制和日志记录两个高阶组件:
const withPermission = (WrappedComponent) => {
return (props) => {
// 权限检查逻辑
if (props.hasPermission) {
return <WrappedComponent {...props} />;
}
return null;
};
};
const withLogging = (WrappedComponent) => {
return (props) => {
console.log('Component rendered');
return <WrappedComponent {...props} />;
};
};
// 合并高阶组件
const withPermissionAndLogging = (WrappedComponent) => {
return (props) => {
if (props.hasPermission) {
console.log('Component rendered with permission');
return <WrappedComponent {...props} />;
}
return null;
};
};
2. 设计模式方面
- 使用装饰器模式:在 TypeScript 中可以使用装饰器来更简洁地组合高阶组件。首先,确保项目配置支持装饰器语法。
import { Component } from'react';
// 权限控制装饰器
function withPermission(target: any) {
return class extends Component<any, any> {
render() {
if (this.props.hasPermission) {
return <target {...this.props} />;
}
return null;
}
};
}
// 日志记录装饰器
function withLogging(target: any) {
return class extends Component<any, any> {
componentDidMount() {
console.log('Component mounted');
}
componentDidUpdate() {
console.log('Component updated');
}
render() {
return <target {...this.props} />;
}
};
}
@withPermission
@withLogging
class MyComponent extends Component<any, any> {
render() {
return <div>My Component</div>;
}
}
- 采用反向继承模式:通过反向继承高阶组件可以更好地控制渲染逻辑和复用代码。例如:
const withDataCache = (WrappedComponent) => {
return class extends WrappedComponent {
constructor(props) {
super(props);
this.cache = {};
}
render() {
const { key } = this.props;
if (!this.cache[key]) {
this.cache[key] = super.render();
}
return this.cache[key];
}
};
};
通过上述方法,可以在提高性能的同时,增强代码的可维护性,使得复杂的高阶组件组合更易于管理。