함수형
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
setTimeout(() => {
reactotron.log(`You clicked ${count} times`);
}, 3000);
});
return (
<View>
<Text>You clicked {count} times</Text>
<TouchableOpacity onPress={() => setCount(count + 1)}>
Click me
</TouchableOpacity>
</View>
);
}
클래스형 1
class Counter1 extends Component {
state = {
count: 0
};
componentDidMount() {
setTimeout(() => {
reactotron.log(`You clicked ${count} times`);
}, 3000);
}
componentDidUpdate() {
setTimeout(() => {
reactotron.log(`You clicked ${count} times`);
}, 3000);
}
render() {
return (
<View>
<Text>You clicked {this.state.count} times</Text>
<TouchableOpacity onPress={() => this.setState({
count: this.state.count + 1
})}>
Click me
</TouchableOpacity>
</View>
)
}
}
클래스형 2 (closure)
class Counter2 extends Component {
state = {
count: 0
};
componentDidMount() {
const count = this.state.count;
setTimeout(() => {
console.log(`You clicked ${count} times`);
}, 3000);
}
componentDidUpdate() {
const count = this.state.count;
setTimeout(() => {
console.log(`You clicked ${count} times`);
}, 3000);
}
render() {
return (
<View>
<Text>You clicked {this.state.count} times</Text>
<TouchableOpacity onPress={() => this.setState({
count: this.state.count + 1
})}>
Click me
</TouchableOpacity>
</View>
)
}
}