데이터를 컨트롤하는 방법에는 두 가지가 있다. 하나는 앞서 말한 props이고 다른 하나가 state이다. prop와 달리 state는 변화하는 데이터를 다룰때 사용해야 한다.
생성자에 state를 초기화 해주고, 변화가 생길때마다, setState를 불러 업데이트 해주어야한다.
예를 들어 계속 깜빡거리는 어떤 text가 있다고 하자. text의 문구 자체는 변하지 않으므로 prop이다. 그러나, 깜빡거리는 상태는 계속 변하므로, State이다.
import React, { Component } from 'react';
import { Text, View } from 'react-native';
class Blink extends Component {
componentDidMount(){
// Toggle the state every second
setInterval(() => (
this.setState(previousState => (
{ isShowingText: !previousState.isShowingText }
))
), 1000);
}
//state object
state = { isShowingText: true };
render() {
if (!this.state.isShowingText) {
return null;
}
return (
<Text>{this.props.text}</Text>
);
}
}
export default class BlinkApp extends Component {
render() {
return (
<View>
<Blink text='I love to blink' />
<Blink text='Yes blinking is so great' />
<Blink text='Why did they ever take this out of HTML' />
<Blink text='Look at me look at me look at me' />
</View>
);
}
}
setState가 호출되면, BlinkApp이 컴포넌트를 re-render 할 것이다. 위의 예시에서는 1초마다 re-render해준다. 즉, 처음에 isShowingText를 true로 설정해주고, 1초마다 이전 값의 반대값을 할당해준다. true일 경우는 text를 출력해주고, false일 경우, text를 출력해주지 않기 때문에 text가 깜빡거릴 것이다.