官术网_书友最值得收藏!

Adding a state to a component

One can say that React barely has any API. It has about 9-10 methods and that is all we get.

The State is one of the main APIs in React. The best place to define the initial state of a component is in the class constructor.

Create a class component and initialize its state:

class Button extends React.Component 

{
constructor(props){
super(props)
this.state = {text: 'OFF'}
this.handleClick = this.handleClick.bind(this)
}
handleClick(){
this.state.text === 'OFF' ? this.setState({text: 'ON'}) :
this.setState({text: 'OFF'})
}
render() {
return (
<button type="button" onClick={this.handleClick}>
{this.state.text}</button>)
}
}

This is an example of an internal state of a button that changes its text on user click (it toggles between ON and OFF).

A few things are required for that component to maintain a state:

  • We defined the state in the class constructor method. This is the first entry of the class that will be executed. We can think of that definition as the default state of the component.
  • We created a handleClick() method and bound it to the this class in the class constructor. It will fire when the user clicks on the button.
  • In the handleClick method, we used one of the React's APIs--this.setState--and based on the comparison of the current state, we set our new state.
React is built with functional purity in mind, and if you set the state directly as this.state.text = 'OFF', the component will not re-render.
  • In the button, we added a simple JavaScript event--onClick. Here, React has a slightly different syntax on events; it uses camel case. onClick becomes onClick.

The second form of the setState() method is passing a function in the state instead of an object; in the callback, we get the previous state:

this.setState
(function(prevState) {
return {
text: prevState.text === 'OFF' ? 'ON' : 'OFF'
};
});

Alternatively, an arrow ES6 function can be used:

this.setState((prevState) => ({
text: prevState.text === 'OFF' ? 'ON' : 'OFF'
}));

Other React methods.

A few other important React APIs are the component life cycles methods:

class Greeting extends React.Component {
constructor(props) {
super(props);
console.log('constructor');
}
componentDidMount() {
console.log('componentDidMount');
}
componentWillUnmount() {
console.log('componentWillUnmount');
}
render() {
return (
<div>
<p>{this.props.name}</p>
{this.props.children}
</div>)
}
}

Let's test these life cycle methods by adding a simple button to the body of the HTML:

<button onclick="umountComponent()">Unmount</button>

Also, we can define that function in the JavaScript tag, as follows:

function umountComponent(){
ReactDOM.unmountComponentAtNode(document.getElementById('root'))
}

When the app is loaded, the order of the events is as follows:

  1. Constructor method is called.
  2. componentDidMount() is called when the component is mounted to a parent or directly to the DOM.
  3. componentWillUnmount() is called just before the component will unmount from the DOM.

A simple use of these events can be as shown:

  1. Constructor: Initialize the component's default state in the constructor.
  2. componentDidMount(): The component is ready. You can perform any actions at that point.
  3. componentWillUnmount(): The component will be detached from the DOM; here, you can clear any resources that may cause memory leaks.
主站蜘蛛池模板: 红桥区| 麦盖提县| 健康| 临沧市| 竹溪县| 和林格尔县| 肇东市| 咸阳市| 太和县| 广安市| 股票| 磐安县| 新民市| 班玛县| 黔南| 平潭县| 同心县| 基隆市| 台北县| 白河县| 塘沽区| 商南县| 仪陇县| 都江堰市| 安仁县| 福鼎市| 孝义市| 新密市| 无锡市| 嘉兴市| 高安市| 东乡县| 泗洪县| 东乌珠穆沁旗| 甘谷县| 白河县| 英德市| 宁阳县| 肥东县| 鸡东县| 榆社县|