isSubmitting
по умолчанию - false
, и после отправки я переключаю его на true
, после этого я устанавливаю тайм-аут, чтобы вернуть его обратно на false
. но почему-то он не возвращается к false
см. закомментированный код
Это - это как работают закрытия
, но как это просто js, у меня нет такой проблемы? звучит так, как будто это связано с useState?
Да, просто JS у вас такая же проблема. Я покажу вам:
let storedValue = false;
function setStoredValue(newValue) {
storedValue = newValue
}
// useState() is basically this; more or less.
// The place where `storedValue` and `setStoredValue` are kept is differrent,
// but that's not relevant to the issue at hand.
function gimmeTheValueAndASetter() {
return [
storedValue,
setStoredValue
]
}
function Element(label) {
// you create a local **constant** copy of the state at this moment
const [localValue, setStoredValue] = gimmeTheValueAndASetter();
// and all your logs here are based off of this local **constant**!
console.log(label, "#1 local:", localValue, " stored:", storedValue);
setStoredValue(!localValue);
console.log(label, "#2 local:", localValue, " stored:", storedValue);
setTimeout(() => {
console.log(label, "#3 local:", localValue, " stored:", storedValue);
setStoredValue(!localValue);
console.log(label, "#4 local:", localValue, " stored:", storedValue);
}, 100);
}
// render Element
Element("first render");
console.log("after first render:", storedValue);
Element("second render");
.as-console-wrapper{top:0;max-height:100%!important}
Вернуться к вашему коду. Вместо того, чтобы переворачивать состояние, лучше установить явное значение. Это также проще рассуждать о:
const onSubmit = (e) => {
e.preventDefault();
// we don't want to submit while another submit is still in progress
// right?
if(isSubmitting) return;
setIsSubmitting(true);
setTimeout(() => {
createProfile(formData, history, edit);
setIsSubmitting(false);
}, 1500);
};
Разве это не проще рассуждать, чем то, что у вас было раньше? isSubmitting
было false
, тогда я перевернул его на true
, так что теперь мне нужно перевернуть его снова, чтобы вернуться к false
, ...