Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How React Component state is going #4

Open
RayJune opened this issue Feb 22, 2018 · 0 comments
Open

How React Component state is going #4

RayJune opened this issue Feb 22, 2018 · 0 comments

Comments

@RayJune
Copy link
Owner

RayJune commented Feb 22, 2018

React component state allows our components to manage some data.

So just think about an object with various key-value pairs , and when that data changes the component will automatically re-render to reflect those changes.

All we have to do is manipulate the data and the component is going to take care of re-rendering itself.

  1. Setup default state object
  2. Component rendered with default state values
  3. Change state based on event
  4. Component re-rendered using new states
  5. start at 3 again

this.setState can handle this situation:

demo MagicalCounter:

class MagicalCounter extends React.Component {
  constructor(props) {
    super(props);
    this.handleAddOne = this.handleAddOne.bind(this);
    this.state = {
      count: 0
    };
  }
  handleAddOne() {
    // this.state.count += 1; can't re-render automatically
    this.setState((prevState) => {
      return {
        count: prevState.count + 1
      };
    });
    console.log(this.state.count);
  }
  render() {
    return (
      <div>
        <h1>Magical Counter:{this.state.count}</h1>
        <button onClick={this.handleAddOne}>+1</button>
      </div>
    )
  }
}

ReactDOM.render(<MagicalCounter />, document.getElementById('app'));
@RayJune RayJune changed the title how react component state is going How React component state is going Feb 23, 2018
@RayJune RayJune changed the title How React component state is going How React Component state is going Feb 23, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant