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

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.
主站蜘蛛池模板: 沅陵县| 太和县| 北川| 泊头市| 棋牌| 冕宁县| 瑞安市| 灵寿县| 威远县| 建昌县| 亚东县| 东台市| 寿阳县| 南丰县| 林周县| 辽阳县| 广丰县| 衡山县| 额敏县| 邢台市| 奉化市| 新邵县| 雷波县| 庆安县| 东平县| 琼海市| 吉木萨尔县| 湛江市| 道真| 故城县| 卓资县| 伊金霍洛旗| 当涂县| 东至县| 河曲县| 府谷县| 福鼎市| 濉溪县| 遂宁市| 丰都县| 津市市|