类组件到函数组件的迁移
公司之前的部分组件功能并不复杂,迁移的成本并不高。这里简单总结一下,将几个类组件改写成函数式组件的收获。
步骤
简单的概括以下四步
- 删除类组件的定义和类的继承
- 将状态变量和生命周期方法用Hooks来替代
- 删除render方法
- 导入React和所需的Hooks
类组件的定义和类的继承
把类组件的定义和类组件的继承删掉,那我们肯定要理解定义和继承到底带来了什么。
原来的定义和继承是用于定义类组件的结构和行为的。React的类组件是通过继承React.Component类来定义的,我们看看源码,发现Component里定义了状态变量、props、还有forceUpdate。
function Component(props, context, updater) {
this.props = props;
this.context = context;
// If a component has string refs, we will assign a different object later.
this.refs = emptyObject;
// We initialize the default updater but the real one gets injected by the
// renderer.
this.updater = updater || ReactNoopUpdateQueue;
}
Component.prototype.setState = function (partialState, callback) {
if (
typeof partialState !== 'object' &&
typeof partialState !== 'function' &&
partialState != null
) {
throw new Error(
'setState(...): takes an object of state variables to update or a ' +
'function which returns an object of state variables.',
);
}
this.updater.enqueueSetState(this, partialState, callback, 'setState');
};
Component.prototype.forceUpdate = function (callback) {
this.updater.enqueueForceUpdate(this, callback, 'forceUpdate');
};
生命周期方法也是该类的一部分,用于处理组件的各个阶段。这些生命周期方法是React提供的钩子,允许你在不同的时刻执行自定义代码,以满足组件的需求。
将状态变量和生命周期方法用Hooks来替代
componentDidMount 和 componentWillUnmount
这两个生命周期的方法可以用useEffect来替代
useEffect(() => {
// 执行初始化操作
return () => {
// 执行清除操作(相当于componentWillUnmount)
};
}, []);
componentDidUpdate可以在useEffect中添加依赖项来替代
useEffect(() => {
// 执行更新操作
}, [dependency1, dependency2]);
shouldComponentUpdate是用来决定是否重新渲染组件的生命周期方法,可以用React.memo来实现类似的优化
import React, { memo } from 'react';
function MyComponent(props) {
// 组件内容
}
export default memo(MyComponent, (prevProps, nextProps) => {
// 自定义相等性检查逻辑
return true; // 如果需要更新,返回 false
});