我试图在formik提交响应后获得成功时将值设置为变量,该变量用于控制成功消息组件
const [loading, setLoading] = React.useState(false);
const [recovered, setRecovered] = React.useState(false);
const dispatch = useDispatch();
const handleSubmit = async (values) => {
setLoading(true);
const response = await dispatch(recoveryPassword(values.email))
setLoading(false);
if (response.status === 200) {
setRecovered(true)
}
}
<Formik
validateOnChange={false}
initialValues={{ email: '' }}
onSubmit={handleSubmit}
>
{({
handleSubmit,
}) => (
<form className="forgot-password__form" onSubmit={handleSubmit}>
<Field
label="Seu email"
color={mainColor}
name="email"
component={TextInput}
style={{
marginTop: 0
}}
/>
<div className="forgot-password__form-button">
<Button
theme="primary"
title="Recuperar senha"
weight="normal"
textcolor={WHITE}
background-color={mainColor}
type="submit"
loading={loading}
/>
</div>
</form>
)}
</Formik>
actions.js
export const recoveryPassword = (email) => async dispatch => {
return post('/users/forgot-password', { email }).then((response) => {
dispatch({ type: ACTION_TYPE.RECOVERED, payload: response.data });
return response;
}).catch((error) => {
dispatch({ type: ACTION_TYPE.RECOVERY_FAILED, payload: error.data });
if (error.data.hasOwnProperty('message')) {
dispatch({
type: NOTIFICATION_TYPE.SHOW_NOTIFICATION, payload: {
variant: 'error',
notificationMessage: error.data.message
}
});
} else {
dispatch({
type: NOTIFICATION_TYPE.SHOW_NOTIFICATION, payload: {
variant: 'error',
notificationMessage: 'Ocorreu um erro ao tentar solicitar o reset de senha'
}
});
}
return error;
});
};
Formik onSubmit
调用handlesSubmit
。当代码到达setLoading(false)
然后到达setRecovered(true)
时,它会发出警告:
警告:无法在已卸载的组件上执行React状态更新。 这是空操作,但它表明应用程序中发生内存泄漏。 要修复,请取消useEffect中的所有订阅和异步任务 清理功能。
loading
变量(setLoading
正在修改)正在被修改。但是recovered
(由setRecovered
)不是