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

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.
主站蜘蛛池模板: 四川省| 安达市| 吉首市| 义马市| 永昌县| 兴城市| 永福县| 房产| 垫江县| 嘉善县| 诸城市| 桂林市| 高邑县| 涿鹿县| 黄浦区| 双峰县| 广东省| 祁门县| 佛山市| 禹城市| 九江市| 康马县| 临夏县| 新野县| 长汀县| 扎赉特旗| 阿拉善左旗| 金湖县| 无极县| 余干县| 林西县| 绥化市| 三穗县| 瓦房店市| 镇巴县| 莆田市| 岐山县| 望江县| 吉林市| 礼泉县| 绍兴市|