*state값을 변경하는 방법
1. setCounter(987); -> 직접 새로운 값을 입력하는 방법 (문자도 가능)
2. setCounter(Counter + 1); -> 이전 값을 이용해서 현재 값을 계산하는 방법
ㄴ 이전 값을 기반으로 계산하고 싶다면 함수를 이용하는 것이 안전하다!
이유 : 다른 곳에서 예상치 못한 업데이트가 될 때 혼동을 주는 것을 방지할 수 있다.
ㄴ setCounter ((current) => current +1); 현재값을 바탕으로 나올 수 있게 한다.
<!DOCTYPE html>
<html>
<body>
<div id="root"></div>
</body>
<script src="https://unpkg.com/react@17.0.2/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@17.0.2/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script type="text/babel">
const root = document.querySelector("#root");
function App() {
const [counter, setCounter] = React.useState(0);
const onClick = () => {
//setCounter(counter+1);
setCounter((current)=>current+1);
};
return (
<div>
<h3>Total clicks: {counter}</h3>
<button onClick={onClick}>Click me</button>
</div>
);
};
ReactDOM.render(<App />, root);
</script>
</html>
반응형
'프론트엔드 > react' 카테고리의 다른 글
| React (5) - MinutesToHours, KmToMiles Converter (0) | 2023.04.20 |
|---|---|
| React (5) - Converter, 삼항연산자 (0) | 2023.04.19 |
| React (4) - Set State, Modifier, Auto Render (1) | 2023.04.18 |
| React (3) - Set State, Good React! (0) | 2023.04.18 |
| React (2) - React Event 동작 #2 (JSX) (0) | 2023.04.17 |