후크를 사용할 때 상태가 업데이트되기를 기다립니다.
Hooks를 사용하여 상태가 업데이트되기를 기다리는 방법양식을 제출할 때 다음 사항을 확인해야 합니다.termsValidation추가 코드를 실행하기 전에 false가 됩니다.만약 주가 바뀌었을 뿐이라면 이것은 이해되지 않는다.
import React, { useState } from 'react';
export default function Signup() {
const [terms, setTerms] = useState('');
const [termsValidation, setTermsValidation] = useState(false);
function handleSubmit(e) {
e.preventDefault();
if (!terms) {
setTermsValidation(true);
} else {
setTermsValidation(false);
}
if (!termsValidation) {
console.log('run something here');
}
}
return (
<div>
<form>
<input type="checkbox" id="terms" name="terms" checked={terms} />
<button type="submit" onClick={handleSubmit}>
Sign up
</button>
</form>
</div>
);
}
그useState훅은 비동기이지만 다음과 같은 콜백 API는 없습니다.setState상태 갱신을 기다리고 싶다면, 필요한 것은,useEffect후크:
import React, { useState, useEffect } from 'react';
export default function Signup() {
const [terms, setTerms] = useState('');
const [termsValidation, setTermsValidation] = useState(false);
useEffect(() => {
if (!termsValidation) {
console.log('run something here');
}
}, [termsValidation]);
function handleSubmit(e) {
e.preventDefault();
if (!terms) {
setTermsValidation(true);
} else {
setTermsValidation(false);
}
}
return (
<div>
<form>
<input type="checkbox" id="terms" name="terms" checked={terms} />
<button type="submit" onClick={handleSubmit}>
Sign up
</button>
</form>
</div>
);
}
다음과 같은 상태 변화setTermsValidation비동기 액션입니다.즉, 즉시는 아니고, 프로그램은 대기하지 않습니다.불이 나서 잊어버려요.따라서, 당신이 전화할 때setTermsValidation(true)프로그램은 termValidation이 true로 변경되기를 기다리는 대신 다음 블록을 계속 실행합니다.따라서 검증이라는 용어는 이전 값을 그대로 유지합니다.
그냥 이렇게 하면 돼
function handleSubmit(e) {
e.preventDefault();
if (!terms) {
setTermsValidation(true);
} else {
setTermsValidation(false);
// assuming you want to run something when termsvalidation turn to false
console.log('run something here');
}
}
또는 useEffect() 후크를 사용하는 것이 이상적입니다.
useEffect(() => {
if (!termsValidation) {
console.log('run something here');
}
}, [termsValidation]);
그러나 useEffect는 초기 렌더링에서도 실행되므로 주의하십시오.
이러한 상황에서는 useRef를 생각할 수 있습니다.useState와 useEffect는 당연히 있어야 하지만 상태를 추적하고 관리하는 논리는 다소 번거로울 수 있을 뿐만 아니라 컴포넌트의 불필요한 재렌더(그 상태가 렌더링 출력의 일부가 되지 않을 때)를 일으킬 수 있습니다.OP의 예로서 다음을 들 수 있습니다.
import React, { useState, useRef } from 'react';
export default function Signup() {
const [terms, setTerms] = useState('');
const termsValidation = useRef(false);
function handleSubmit(e) {
e.preventDefault();
if (!terms && !termsValidation.current) {
termsValidation.current = true;
console.log('run something here');
termsValidation.current = false; // when its finished running
}
}
return (
<div> etc
);
}
언급URL : https://stackoverflow.com/questions/55174588/wait-for-state-to-update-when-using-hooks
'source' 카테고리의 다른 글
| JavaScript 개체를 JSON 문자열로 직렬화 (0) | 2023.03.13 |
|---|---|
| ngTrueValue 및 ngFalseValue의 수치 설정 (0) | 2023.03.13 |
| 키를 문자열로, 값을 맵 반복으로 포함하는 ngFor 루프 맵을 사용하여 반복하는 방법 (0) | 2023.03.13 |
| POST 요청보다 GET 요청을 사용하는 이점은 무엇입니까? (0) | 2023.03.08 |
| 컨스트럭터 vs componentWillMount. componentWillMount는 컨스트럭터로는 할 수 없는 일을 componentWillMount는 어떻게 할 수 있습니까? (0) | 2023.03.08 |