Answer a question

I know that state allows us to create components that are dynamic and interactive but I want to deep in state.

Can someone help me to understand state in React using a real life example?

Answers

import React from 'react';

class App extends React.Component {
  state = {
    count: 0
  };

  render() {
    return (
      <div>
        <h1>Hello world</h1>
        <h2>Count: {this.state.count}</h2>
        <button
          onClick={() => this.setState(state => ({ count: state.count + 1 }))}
        >
          +
        </button>
        <button
          onClick={() => this.setState(state => ({ count: state.count - 1 }))}
        >
          -
        </button>
      </div>
    );
  }
}

export default App;

In the above code, it has a state object with property/state: count.

State can simply be understand as a value at that point of time of the particular component/app. In the above example, when the app is first running, the app is with state count === 0

As we can see there are two buttons + and - that update the value using this.setState, it simply update the "state" of count for the app, and the app will re-render, whenever the state change

Logo

React社区为您提供最前沿的新闻资讯和知识内容

更多推荐