Interview question
How do you handle state in class components? Class components में state कैसे handle करते हैं?
Answer
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0, name: 'John' };
}
// Update state
increment = () => {
this.setState({ count: this.state.count + 1 });
}
// Multiple updates
handleChange = (e) => {
this.setState({ name: e.target.value });
}
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<p>Name: {this.state.name}</p>
<button onClick={this.increment}>Increment</button>
</div>
);
}
}Constructor में initialize करो:
this.state = { count: 0 };
SetState से update करो:
this.setState({ count: this.state.count + 1 });Was this answer clear?