본문 바로가기
개념/React

React) pull out constructor from state

by kiseno 2025. 4. 3.
728x90
반응형
SMALL
import { Component } from "react";

class Counter extends Component{
    state = {
        number : 0,
        fixedNumber : 0
    };
    render(){
        const {number, fixedNumber} = this.state;
        return(
            <div>
                <h1>{number}</h1>
                <h2> Not change value : {fixedNumber}</h2>
                <button onClick={() => {
                    this.setState(({number: number + 1}));
                }}>
                    +1
                </button>
            </div>
        );
    }
}

export default Counter;

### Class Component Definition

1. **Importing Component**:
   ```jsx
   import { Component } from "react";
   ```
   This imports the `Component` class from the React library, which is necessary for creating class components.

2. **Component Definition**:
   ```jsx
   class Counter extends Component {
   ```
   - `Counter` is defined as a class that extends `Component`, making it a React component.

3. **State Initialization**:
   ```jsx
   state = {
       number: 0,
       fixedNumber: 0
   };
   ```
   - The `state` of the component is initialized with two properties: `number` and `fixedNumber`.
   - `number` is used to track the current count, which can be incremented.
   - `fixedNumber` is intended to demonstrate a state value that remains unchanged throughout the component's lifecycle.

4. **Render Method**:
   ```jsx
   render() {
       const { number, fixedNumber } = this.state;
       return (
           <div>
               <h1>{number}</h1>
               <h2> Not change value: {fixedNumber}</h2>
               <button onClick={() => {
                   this.setState(({number}) => ({number: number + 1}));
               }}>
                   +1
               </button>
           </div>
       );
   }
   ```
   - The `render` method outputs the JSX to be displayed in the DOM.
   - It destructures `number` and `fixedNumber` from the component's state for easy access.
   - Displays the current value of `number` in an `<h1>` tag.
   - Shows the unchanged `fixedNumber` in an `<h2>` tag.
   - Includes a button that, when clicked, increments the `number` state by 1. This is done via the `setState` method, which is called with an updater function form, correctly incrementing the `number`. The callback format used in `setState` ensures that updates are based on the previous state, making the increment operation safe from potential asynchronous state update issues.

5. **Export**:
   ```jsx
   export default Counter;
   ```
   - Exports the `Counter` component so it can be imported and used in other parts of the application.

### Corrections and Improvements
There is a minor error in the `onClick` handler for the button:
```jsx
this.setState(({number: number + 1}));
```
This should be corrected to:
```jsx
this.setState(prevState => ({ number: prevState.number + 1 }));
```
This uses the function form of `setState` to correctly update the `number` state based on its previous state, which is a more reliable way to update state that depends on the previous state value, especially when dealing with asynchronous state updates in React.

This component is a good demonstration of basic React state management and event handling in a class component.

728x90
반응형
LIST

'개념 > React' 카테고리의 다른 글

React) out of value to props  (0) 2025.04.05
React) propTypes  (0) 2025.04.04
React) this setState function parameter  (0) 2025.04.02
Reat) click the button print out comment value set empty  (0) 2025.04.01
React) Event basic  (0) 2025.03.31