Development/React.js · Next.js
[React] 클래스형 컴포넌트 - state / state 값 변경하기 / setState() / forceUpdate()
레오나르도 다빈츠
2022. 8. 22. 22:52
◽ state 사용하기
import React from "react";
import './App.css';
import ChildComp from './ChildComp'
function App() {
return (
<div>
<h1>React</h1>
<ChildComp
val_string={'After LIKE'}
/>
</div>
);
}
export default App;
import React, { Component } from "react";
class ChildComp extends Component {
constructor(props) {
super(props);
this.state = {
stateString: this.props.val_string,
stateNumber: 200
}
}
render() {
return (
<div style={{ padding: '20px' }}>
{this.state.stateString}
</div>
);
}
}
export default ChildComp
◽ setState()를 사용하여 값 변경하기
[this.state.변수명 = value] 같이 state를 직적 변경하면 render() 함수가 호출되지않아 값이 변경되지 않는다.
state 값을 변경할 때는 setState()를 사용한다.
import React from "react";
import './App.css';
import ChildComp from './ChildComp'
function App() {
return (
<div>
<h1>React</h1>
<ChildComp />
</div>
);
}
export default App;
import React, { Component } from "react";
class ChildComp extends Component {
constructor(props) {
super(props);
this.state = {
stateString: 'After LIKE',
}
}
stateChange = () => {
this.setState({ stateString: 'Before LIKE' })
}
render() {
return (
<div style={{ padding: '20px' }}>
<button onClick={this.stateChange}></button>
{this.state.stateString}
</div>
);
}
}
export default ChildComp
◽ forceUpdate()를 사용하여 값 변경하기
this.state.stateString = 'Before LIKE'는 render() 함수를 호출하지 않기 때문에 값을 변경하지 않는다.
이 때 forceUpdate() 함수로 화면을 강제로 새로고침하면 render() 함수를 호출하여 변경된 값을 화면에서 확인할 수 있다.
import React, { Component } from "react";
class ChildComp extends Component {
constructor(props) {
super(props);
this.state = {
stateString: 'After LIKE',
}
}
stateChange = () => {
this.state.stateString = 'Before LIKE'
this.forceUpdate()
}
render() {
return (
<div style={{ padding: '20px' }}>
<button onClick={this.stateChange}></button>
{this.state.stateString}
</div>
);
}
}
export default ChildComp
◽ object값 변경하기
function modifyTitle() {
// 원본 오브젝트를 유지하는 것이 좋다.
let copy = [...title] // deep copy 사용
copy[0] = '변경할 텍스트'
setTitle(copy)
}
출처
이정열, 초보자를 위한 리액트 200제 (정보문화사, 2021)