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

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.
主站蜘蛛池模板: 连云港市| 禹城市| 尚义县| 阳原县| 漯河市| 英山县| 都江堰市| 南投县| 晋城| 通许县| 全椒县| 岳西县| 连城县| 文安县| 分宜县| 古丈县| 普陀区| 新民市| 永和县| 昌黎县| 冕宁县| 牟定县| 普格县| 荔波县| 宁陕县| 洪洞县| 丹棱县| 漯河市| 奉贤区| 石家庄市| 凤翔县| 六安市| 宁强县| 沙洋县| 湾仔区| 靖宇县| 贞丰县| 贡山| 乐安县| 会理县| 龙海市|