Here is a demo with commentary code to provide you more information: http://codepen.io/PiotrBerebecki/pen/rrGWjm
1. What is the state on line 3? which look like a global variable, this makes sense if there is var or const in front of it. Is this a function / var life cycle?
state on line 3 is just a property of the Counter component. Another way to initialize state in React using ES6 syntax is as follows:
constructor() { super(); this.state = { value: 0 } }
React docs: https://facebook.imtqy.com/react/docs/reusable-components.html#es6-classes
The [React ES6 class] API is similar to React.createClass, with the exception of getInitialState. Instead of providing a separate getInitialState method , you will create your own state property in the constructor .
2. Do I have to import a component from a reaction? I remember I do not need to do this in v15.
You can also simply import React and define the class as follows:
import React from 'react'; class Counter extends React.Component { ...
You can also use the component API below:
import React, { Component } from 'react'; class Counter extends Component { ...
3. Where does prevState come from?
The previous state comes from setState api: https://facebook.imtqy.com/react/docs/component-api.html#setstate
It is also possible to transfer a function with a signature to a function (state, props). This can be useful in some cases when you want to install an atomic update that asks for the previous state + props value before setting any values. For example, suppose we wanted to increase the value in the state:
this.setState(function(previousState, currentProps) { return { value: previousState.value + 1 }; });
You will often see how developers update the state as follows. This is less reliable than the above method, since the state can be updated asynchronously, and we should not rely on its values ββto calculate the next state.
this.setState({ value: this.state.value + 1
Full code from my code:
class Counter extends React.Component { // state = { value: 0 }; // you can also initialise state in React // in the constructor: constructor() { super(); this.state = { value: 0 } } increment = () => { this.setState(prevState => ({ value: prevState.value + 1 })); } decrement = () => { this.setState(prevState => ({ value: prevState.value - 1 })); } render() { return ( <div> {this.state.value} <button onClick={this.increment}>+</button> <button onClick={this.decrement}>-</button> </div> ) } } ReactDOM.render( <Counter />, document.getElementById('app') );