4

React 类组件转换为函数式 - chanvin

 8 months ago
source link: https://www.cnblogs.com/chanvin/p/transform-class-react-components-to-functional.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

React 类组件转换为函数式

函数式的 React 组件更加现代,并支持有用的 hooks,现在流行把旧式的类组件转换为函数式组件。这篇文章总结了转换的一些通用的步骤和陷阱。

class (\w+) extends Component \{
const $1: FC = () => {
  • 这是没有 exportprops 的场景
(export) default class (\w+) extends Component \{
$1 const $2: FC<$2Props> = () => {
  • 作为第二个捕捉的单词,$2 就是组件名。
  • $2Props 应该定义为 props 的接口名。

Attributes 前缀

this\.(state\.|props\.)?
  • 假设 props 被统一解构。

生命周期函数

componentDidMount() { 
useEffect(() => {}, []);
  • componentDidUpdate 也可以被转换为 useEffect,并设置合适的依赖。
  • componentWillUnmount 可以转换为对应 useEffect 处理函数的返回函数。

State 相关语句

state = {
  data: null,
};
const [data, setData] = useState();
this.setState({
  data,
});
setData(data)
^(\s*)(\w+)\((\w*)\) \{
$1const $2 = ($3) => {
  • 这属于常规函数定义。
  • $1 是空格, $2 是方法名, $3 是参数.
^(\s*)((\w+) = (async )?\((\w+(, )?)*\) =>)
$1const $2
  • 这属于箭头函数定义。
  • $1 是空格, $2 方法名之后的所有内容

类 Getter

^(\s*)(get) (\w+)\(\)
$1const $2\u$3 = () =>
  • \u 表示对后面捕获的单词首字母大写。
  • 对 getter 的调用应该在方法名后加上 ()
  • 如果 getter 很简单,可以直接赋值而不用使用函数。
render() {
  return (
    <></>
  );
}
return (
  <></>
);

值得关注的陷阱

类组件可以具有同名的 attributesprops,例如 this.datathis.props.data
this.data 变为 data,另外 props 经常被解构为 const {data} = props,命名冲突 就产生了。

State 回调

通过 this.setState,我们可以设置一个回调,在 state 确实改变时进行调用,但我们需要把这种方式更新为使用更新的 state 作为依赖的 useEffect

函数 State

如果 state 的值是函数,你需要把这个函数包裹在另一个匿名函数中,否则 hook 版本的 setState 会把这个函数视为回调。
实际上,在大多情况下,这种 state 是和渲染无关的,所以也许使用 useRef 更加合适。

这个文章展示了一些使用 RegExp 的替换,可以使类组件到函数式组件的替换简单点,另外指出了一些在这个过程中你可能会遇到的陷阱,可以特别留意下,不过当然,不同的场景会存在更多的工作要处理。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK