Three major attributes of React components: state

1. Understand

  1. The component is called a "state machine", and the page is statedisplayed based on the data of the component's properties.
    stateIs a mechanism for storing and managing data within components.
    It's a way of tracking state changes within a component so that when data changes, React can update the user interface to reflect those changes. stateThe use of is very important in building interactive and dynamic user interfaces.

  2. State is the most important attribute of the component object, and the value is the object (can contain multiple key-value combinations)

2. Purpose

  1. Data-driven UI updates: state Allows you to store data in components and automatically update the user interface when the data changes. When statechanges occur, React will automatically re-render the relevant component parts so that the latest data is displayed.

  2. Respond to user interactions: By using it state, you can track user interactions with components, such as clicking buttons, entering text, etc. As the user performs actions, you can update stateto reflect those interactions and then trigger updates to the UI.

  3. Dynamic data presentation: When you need to present different UIs based on different conditions or data situations, this statecan help you manage these dynamic changes. You can statedecide what content to display based on the value to achieve a dynamic interface.

  4. Form handling: When dealing with form elements, such as input boxes, checkboxes, etc., you can use to statestore the value entered by the user, and validate and process it as needed. This makes form interaction and data management more convenient.

  5. Inter-component communication: If you have multiple components in your application that need to share some data, you can store these data in the common ancestor component stateand propspass the data to the child components through . This way, you can keep your data synchronized.

There are some rules to follow when using state, for example, you should avoid modifying it directly stateand instead should use setStatethe method to update it. This is because React needs to know when to update components and re-render the interface. Additionally, since statechanges to may be asynchronous, you need to be careful about setStatestate changes between multiple invocations.

3. Use

3.1. Class initialization

import React, {
    
     Component } from 'react';

class MyComponent extends Component {
    
    
  constructor(props) {
    
    
    super(props);

    // 初始化 state
    this.state = {
    
    
      count: 0,
      text: 'Hello, React!',
    };
  }

  render() {
    
    
    return (
      <div>
        <p>{
    
    this.state.text}</p>
        <p>Count: {
    
    this.state.count}</p>
      </div>
    );
  }
}

export default MyComponent;

3.2. Function initialization

It should be noted that since the introduction of Hooks in React 16.8, you can also use useState in function components to initialize and manage state. The following is an example of using useState for state initialization:

import React, {
    
     useState } from 'react';

function MyComponent() {
    
    
  // 初始化 state 使用 useState
  const [count, setCount] = useState(0);
  const [text, setText] = useState('Hello, React!');

  return (
    <div>
      <p>{
    
    text}</p>
      <p>Count: {
    
    count}</p>
    </div>
  );
}

export default MyComponent;

4. Status reading and updating

4.1. Component internal status management and data update

Use state to manage the internal state of the component. When the state changes, React will re-render the component to reflect the latest data. You can use the setState method to update state.

import React, {
    
     Component } from 'react';

class Counter extends Component {
    
    
  constructor(props) {
    
    
    super(props);
    this.state = {
    
    
      count: 0,
    };
  }

  incrementCount = () => {
    
    
    this.setState((prevState) => ({
    
    
      count: prevState.count + 1,
    }));
  };

  render() {
    
    
    return (
      <div>
        <p>Count: {
    
    this.state.count}</p>
        <button onClick={
    
    this.incrementCount}>Increment</button>
      </div>
    );
  }
}
  1. Read display:
    this.state.count
  2. Update status–>Update interface:
    this.setState({count : newValue})

4.2. Use state and props together

State is generally initialized using parameters in props.

Demonstrates not using your own in the child component state, but directly using the one passed by the parent component props:

import React, {
    
     Component } from 'react';

class ParentComponent extends Component {
    
    
  constructor(props) {
    
    
    super(props);
    this.state = {
    
    
      count: props.initialCount,
    };
  }

  incrementCount = () => {
    
    
    this.setState((prevState) => ({
    
    
      count: prevState.count + 1,
    }));
  };

  render() {
    
    
    return (
      <div>
        <p>Parent Count: {
    
    this.state.count}</p>
        <ChildComponent count={
    
    this.state.count} incrementCount={
    
    this.incrementCount} />
      </div>
    );
  }
}

function ChildComponent(props) {
    
    
  return (
    <div>
      <p>Child Count from Parent: {
    
    props.count}</p>
      <button onClick={
    
    props.incrementCount}>Increment Parent Count</button>
    </div>
  );
}

class App extends Component {
    
    
  render() {
    
    
    return <ParentComponent initialCount={
    
    5} />;
  }
}

export default App;

ChildComponentUse the passed from parent component directly countand update the parent component's state by propscalling the method. This method is more concise and clear, and is suitable for situations where the child component only needs to access the data passed by the parent component without maintaining independent state.incrementCount

Guess you like

Origin blog.csdn.net/weixin_35691921/article/details/132619424