无法对带有 react-intl-tel-input 组件的卸载组件执行 React 状态更新



我有一个名为注册的功能组件,其中我使用react-intl-tel-input作为移动号码字段。提交表单时只有一个异步axios请求。但是我仍然得到这个警告

警告:无法在未挂载的组件上执行React状态更新。这是一个无操作,但它表明应用程序中存在内存泄漏。要修复,请取消componentWillUnmount方法中的所有订阅和异步任务。

我想删除这个警告,但到目前为止,我尝试了Stackoverflow上提供的几个解决方案不工作。经过调试,我发现警告是从react-intl-tel-input<IntlTelInput />字段产生的。请帮我删除这个警告。

代码示例:

import React, {useState} from "react";
import IntlTelInput from "react-intl-tel-input";
import axios from "axios";
function Signup() {
const [password, setPassword] = useState("");
const [email, setEmail] = useState("");
const [mobile, setMobile] = useState("");
const handleSubmit = async (e) => {
const signupData = { email, password, mobile};
const response = await axios.post(/url, signupData);
}
return (
<form onSubmit={handleSubmit}>
<input name="email" type="text" onChange={e => setEmail(e.target.value)} />
<input name="password" type="password" onChange={e => setPassword(e.target.value)} />
<IntlTelInput
containerClassName="intl-tel-input"
inputClassName="form-control w-100"
autoPlaceholder
separateDialCode
defaultCountry="za"
name="mobile"
numberType="MOBILE"
fieldId="mobile_number"
onPhoneNumberChange={(validate, value, countryData) =>
setMobile(value)
}
formatOnInit={false}
autoComplete="new-phone"
/>
<button type="submit">Signup</button>
);
export default Signup;

handleSubmit函数中,尝试在顶部添加e.preventDefault()。默认情况下,当单击提交按钮时,表单组件将尝试将表单提交回服务器,这将导致页面刷新并卸载组件。e.preventDefault()应该首先阻止它尝试提交。

例子
import React, {useState} from "react";
import IntlTelInput from "react-intl-tel-input";
import axios from "axios";
function Signup() {
const [password, setPassword] = useState("");
const [email, setEmail] = useState("");
const [mobile, setMobile] = useState("");
const handleSubmit = async (e) => {
e.preventDefault();
const signupData = { email, password, mobile};
const response = await axios.post(/url, signupData);
}
return (
<form onSubmit={handleSubmit}>
<input name="email" type="text" onChange={e => setEmail(e.target.value)} />
<input name="password" type="password" onChange={e => setPassword(e.target.value)} />
<IntlTelInput
containerClassName="intl-tel-input"
inputClassName="form-control w-100"
autoPlaceholder
separateDialCode
defaultCountry="za"
name="mobile"
numberType="MOBILE"
fieldId="mobile_number"
onPhoneNumberChange={(validate, value, countryData) =>
setMobile(value)
}
formatOnInit={false}
autoComplete="new-phone"
/>
<button type="submit">Signup</button>
</form>
);
export default Signup;

编辑:看起来你也没有添加关闭form标签,所以我只是在上面的代码中添加了它。

相关内容

最新更新