본문 바로가기
개념/React

React) this setState function parameter

by kiseno 2025. 4. 2.
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(prevState =>{
                    //     return {
                    //         number: prevState.number + 1
                    //     };
                    // });
                    this.setState(prevState => ({
                        number :prevState.number + 1
                    }))
                }}>
                    +1
                </button>
            </div>
        );
    }
}

export default Counter;

### Component Overview

1. **Import and Extend Component**:
   ```jsx
   import { Component } from "react";

   class Counter extends Component {
   ```
   This line imports the `Component` base class from the React library, which allows you to create a class component. `Counter` extends `Component`, meaning it inherits methods and properties from React's `Component` class, making it a React component itself.

2. **State Initialization**:
   ```jsx
   state = {
       number: 0,
       fixedNumber: 0
   };
   ```
   Here, the component's state is initialized with two values:
   - `number`: This value will be incremented with each button click.
   - `fixedNumber`: This value is displayed to show that some state values can remain unchanged even after other state updates.

3. **Rendering the Component**:
   ```jsx
   render() {
       const { number, fixedNumber } = this.state;
       return (
           <div>
               <h1>{number}</h1>
               <h2>Not change value: {fixedNumber}</h2>
               <button onClick={this.handleClick}>
                   +1
               </button>
           </div>
       );
   }
   ```
   - The `render` method is a crucial lifecycle method in class components that outputs JSX to be mounted to the DOM.
   - It destructures `number` and `fixedNumber` from the state for use in the returned JSX.
   - Displays `number` in an `<h1>` tag and `fixedNumber` in an `<h2>` tag.
   - Includes a button that triggers a state update to increment `number` when clicked.

4. **Button Click Event Handling**:
   ```jsx
   <button onClick={() => {
       this.setState(prevState => ({
           number: prevState.number + 1
       }));
   }}>
       +1
   </button>
   ```
   - This button, when clicked, invokes an inline function that calls `setState`.
   - `setState` is used with a callback function that receives the previous state (`prevState`) as its argument. This callback returns a new state object with the `number` property incremented by 1.
   - Using `prevState` ensures that the state update is reliable and incorporates any previous updates, which is crucial in scenarios where state updates may be asynchronous and depend on the current state.

5. **Exporting the Component**:
   ```jsx
   export default Counter;
   ```
   - This line makes the `Counter` component available for import and use in other parts of your application.

### Final Thoughts

This example is an excellent demonstration of managing state in React class components, specifically how to handle state updates correctly with `setState` when the new state depends on the old state. The structure and functionality provided are appropriate for simple interactions and serve as a foundational concept for building more complex components in React.

728x90
반응형
LIST

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

React) propTypes  (0) 2025.04.04
React) pull out constructor from state  (0) 2025.04.03
Reat) click the button print out comment value set empty  (0) 2025.04.01
React) Event basic  (0) 2025.03.31
React) Event Practice 1  (0) 2025.03.30