面试题答案
一键面试实现过程
- 安装 Formik:在项目中通过 npm 或 yarn 安装
formik
,例如npm install formik
。 - 创建 React 组件并使用 Formik:
import React, { Component } from'react';
import { Formik, Form } from 'formik';
class MyForm extends Component {
constructor(props) {
super(props);
// 初始化状态等操作
}
componentWillUnmount() {
// 取消任何未完成的异步操作,如 API 请求
if (this.unsubscribe) {
this.unsubscribe();
}
}
render() {
return (
<Formik
initialValues={{ username: '', password: '' }}
onSubmit={(values, { setSubmitting }) => {
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
setSubmitting(false);
}, 400);
}}
>
{({ isSubmitting }) => (
<Form>
<label htmlFor="username">Username</label>
<input type="text" id="username" name="username" />
<label htmlFor="password">Password</label>
<input type="password" id="password" name="password" />
<button type="submit" disabled={isSubmitting}>
Submit
</button>
</Form>
)}
</Formik>
);
}
}
export default MyForm;
在上述代码中:
- 初始化表单:使用
Formik
提供的initialValues
初始化表单值。 - 提交表单:通过
onSubmit
定义表单提交逻辑。 componentWillUnmount
方法:在组件即将卸载时,取消任何未完成的异步操作。例如,如果在表单中有进行 API 请求,在componentWillUnmount
中取消该请求(假设存在一个取消订阅的函数unsubscribe
)。
原理
- 内存泄漏原因:当组件卸载时,如果有未完成的异步操作(如 API 请求)仍然引用着组件实例,垃圾回收机制无法回收该组件占用的内存,从而导致内存泄漏。
componentWillUnmount
的作用:componentWillUnmount
是 React 组件生命周期方法,在组件从 DOM 中移除之前调用。在这里取消未完成的异步操作,使得没有外部引用指向组件实例,垃圾回收机制就可以回收组件占用的内存,优化内存使用,避免潜在的内存泄漏问题。- Formik 与组件生命周期结合:Formik 主要负责表单的状态管理和验证等功能。在使用 Formik 的 React 组件中,合理利用
componentWillUnmount
生命周期方法,可以在组件卸载时处理好与表单相关的异步操作,确保内存的正确回收,优化整个应用的性能。