reject:state

This is an old revision of the document!


state

state is a special variable that represent the state of a Component. Any class that extends Component from 'react' can have this. Usually the state variable contains a map of variables. React will monitor it, and if it is changed, the view using the variables in state will also be updated.

Here is an example that when the button is clicked, the state of the App component will be updated. Note that we need to use the method this.setState() to update the state variable, and the setState method will only update the related variables, and leave the already defined variable remain unchanged.

import React, { Component } from 'react';
import './App.css';
import Person from './Person/Person';

class App extends Component {
  state = {
    persons: [
      { name: "Abc", age: "11" },
      { name: "Def", age: "22" },
      { name: "Ghi", age: "33" },
    ],
    somethingElse: "somethingElse"
  }

  onButtonClicked = () => {
    this.setState({    persons: [
      { name: "WTF?!", age: "11" },
      { name: "Def", age: "22" },
      { name: "Ghi", age: "33" },
    ]
})
    console.log("clicked");
  }

  render() {
    return (
      <div className="App">
        <button onClick={this.onButtonClicked}>Click</button>
        <h1>Reacsst!</h1>
        <Person name={this.state.persons[0].name} age={this.state.persons[0].age}>This is a demo</Person>
      </div >
    )
  }
}

export default App;

When the button is clicked, the persons in state will be updated, and the somethingElse will remain unchanged.

  • reject/state.1578294457.txt.gz
  • Last modified: 2020/01/06 15:07
  • by chongtin