Reactjs 反应:Can';t使用Formik对未安装的组件执行React状态更新
我有以下组件。调用onSubmit方法Reactjs 反应:Can';t使用Formik对未安装的组件执行React状态更新,reactjs,react-hooks,formik,yup,Reactjs,React Hooks,Formik,Yup,我有以下组件。调用onSubmit方法 export const LoginForm = () => { const [loading, setLoading] = React.useState(false); const classes = useStyles(); const navigate = useNavigate(); const onSubmit = (values, actions) => { setLoading(tr
export const LoginForm = () => {
const [loading, setLoading] = React.useState(false);
const classes = useStyles();
const navigate = useNavigate();
const onSubmit = (values, actions) => {
setLoading(true);
axios({
method: 'POST',
url: `localhost:3000/api/accounts/login`,
data: values,
headers: {
'CONTENT-TYPE': 'application/json'
}
})
.then(response => {
localStorage.setItem('user', JSON.stringify(response.data));
navigate('/', { replace: true });
setLoading(false);
})
.catch(error => {
actions.setFieldError('general', 'Something went wrong');
actions.setSubmitting(false);
setLoading(false);
});
};
<Formik
initialValues={{ email: '', password: '' }}
validationSchema={Yup.object().shape({
email: Yup.string()
.email('Must be a valid email')
.max(255)
.required('Email is required'),
password: Yup.string()
.max(255)
.required('Password is required')
})}
onSubmit={onSubmit}
>
}
我没有使用
useffect
钩子,所以我不知道发生了什么事没错,消息可能有点混乱,因为您没有使用useffect
钩子,但是在卸载组件后尝试更新状态的问题并不严格限于useffect
。任何异步处理的代码都可能导致此错误。我猜应该是在命令导航发出后立即排队的状态更新。您导航到另一条路线,然后装载此LoginForm
组件
我认为您可以删除设置加载(false)代码>当导航离开页面时
const onSubmit = (values, actions) => {
setLoading(true);
axios({
method: 'POST',
url: `localhost:3000/api/accounts/login`,
data: values,
headers: {
'CONTENT-TYPE': 'application/json'
}
})
.then(response => {
localStorage.setItem('user', JSON.stringify(response.data));
navigate('/', {
replace: true
});
// remove the state update that was here
})
.catch(error => {
actions.setFieldError('general', 'Something went wrong');
actions.setSubmitting(false);
})
.finally(() => {
setLoading(false);
});
};
setLoading(false)由于导航原因,在卸载formik时可能会调用code>。是的,通过从finally块中删除setLoading(false),问题就消失了。谢谢
const onSubmit = (values, actions) => {
setLoading(true);
axios({
method: 'POST',
url: `localhost:3000/api/accounts/login`,
data: values,
headers: {
'CONTENT-TYPE': 'application/json'
}
})
.then(response => {
localStorage.setItem('user', JSON.stringify(response.data));
navigate('/', {
replace: true
});
// remove the state update that was here
})
.catch(error => {
actions.setFieldError('general', 'Something went wrong');
actions.setSubmitting(false);
})
.finally(() => {
setLoading(false);
});
};