给React初学者的10分钟ES6教程

原文: The 10 min ES6 course for the beginner React Developer
译者:Jim Xiao

著名的80/20定律能够用来解释React和ES6的关系。由于ES6增长了超过75个新特性,可是根据我自身学习React经验,只使用了不到20%的ES6新特性。git

注意: 在这篇文章中,为了不引发混淆,我把JavaScript近似等同于ECMAScript(ES), 而ES6 = ES5 + 新特性,因此ES6和ES5都至关于JavaScript。他们之间的区别就是支持不一样的语法以及ES6新加了一些功能。数组

当我从Angular 1和纯ES5转到React时,我看了一些教程,当了解到箭头函数和解构语句时,我十分迷惑,不知道哪些语法来自React, 哪些语法来自ES6。app

可是在大概一周以后,我基本上肯定了,像{name}这样的语法只能写在React中(说明该语法不是来自ES6)。函数

这并非一个完整的教程,只是我在React代码中使用ES6的小结。那咱们开始吧。工具

Let和const

在旧版的JavaScript (ES5)中,咱们使用关键字var来声明变量, 利用JavaScript变量提高的黑魔法, 咱们甚至能够在没有声明变量前,就使用该变量:学习

// ES5
console.log(myVar); // undefined
var myVar = 10;

这种变量提高可能带来一些难以预见的结果。可是在ES6就不会存在了。经过使用let或者const关键字,你必须先声明变量,才能使用它:网站

// ES6
console.log(myVar) // ReferenceError: myVar is not defined
let myVar = 10

从下面的结果能够看出,constlet的不一样在于,用const声明变量,该变量值是不能更改的,而let能够更改:this

// ES6
let x = 10
const y = 20
x = 25 // Ok
y = 30 // TypeError: Assignment to constant variable.

再也不使用分号

ES6以及全部相关的工具都很好地支持了自动分号插入。因此,ES6的代码中能够几乎去掉全部的分号, 使代码看起来更加简洁:prototype

//ES5
var theNumber = 10;
console.log(theNumber);

//ES6 - 能够去掉分号
let theNumber = 10
console.log(theNumber)

这并非一个很大的改动,但确实是让代码看起来更舒服,尤为当你是CoffeeScript代码风格的粉丝。code

箭头函数

在ES5语法中,若是声明一个函数,须要这样写:

// ES5
var sum = function(a, b) {
   return a + b
}

在ES6中,你能够经过箭头函数快速声明函数:

// ES6
const sum = (a, b) => {return a + b}

而且,若是你只须要简单的一行函数,甚至能够去掉return关键字

// ES6
const sum = (a, b) => a + b // 一行箭头函数会自动返回结果

还有很是重要的一点,就是箭头函数的this是绑定了父级做用域的上下文:

function DogWorldContext() {
  this.age = 0

  setInterval(function growUp() {
    this.age++
    console.log(this.age)
  }, 1000)
}
var worldWithStandardFunction = new DogWorldContext()
// 将会每秒打印NaN,由于growUp是普通函数,它有本身this关键字的指向
function DogWorldContext() {
  this.age = 0

  setInterval(()=> {
    this.age++
    console.log(this.age)
  }, 1000)
}
var worldWithArrowFunction = new DogWorldContext()
// 将会每隔1s打印出1,2,3...

箭头函数没有本身的this绑定。该this上下文就是父级做用域的上下文,本例子中,就是DogWorldContext

解构

知名开发者网站Developer.mozillar.org对解构的定义是: 从数组和函数中提取值,并存储为变量。

提取对象的属性值是很是常见的作法。好比下面的代码:

// ES5; this.props.user = {name: "Daniel", age : 32}
alert(this.props.user.name + " " + this.props.user.age);

为了使之更易读, 咱们把属性值赋给变量:

// ES5; this.props.user = {name: "Daniel", age : 32}
var name = this.props.user.name;
var age = this.props.user.age;
alert(name + " " + age);

在ES6中,咱们可使用对象解构:

// ES6; this.props.user = {name: "Daniel", age : 32}
const {name} = this.props.user
const {age} = this.props.user
alert(name + " " + age)

咱们甚至能够简写为一行:

// ES6; this.props.user = {name: "Daniel", age : 32}
const {name, age} = this.props.user
alert(name + " " + age)

对象字面量

ES6容许咱们用更少的代码表示对象键值对。

// ES5
str = "HELLO"
number = 20
obj = {
   str: str,
   number: number
}

在ES6中,上面的代码能够变为:

// ES6
str = "HELLO"
number = 20
obj = { str, number} //  obj = {str: "HELLO", number: 20}

类,构造器和方法

之前的JavaScript没有class这个关键字,为了建立一个简单的Dog类,须要使用构造函数来模拟这个类:

// ES5
function Dog(name, weight){
  this.name = name;
  this.weight = weight;
}

Dog.prototype.speak = function(){
    alert("Woof, woof … my name is: " + this.name);
};

// 用new关键字初始化对象
var dog = new Dog("Spike", 25);

// 调用方法
dog.speak(); // alerts “Woof, woof … my name is: Spike”

你能够经过ES5的构造函数获得一个基本的对象和该对象的方法,可是并无获得”开箱即用”的类。那么看看ES6的class是怎么作的:

//ES6
class Dog {
   constructor(name, weight) {
      this.name = name
      this.weight = weight
   }
   speak() {
     alert("Woof, woof … my name is: " + this.name)
   }
}
const dog = new Dog("Spike", 25)
dog.speak()

类的继承和React

ES5中能够经过原型链继承的方式实现继承。可是在ES6中,能够经过关键字extends来实现类的继承:

var Greeting = createReactClass({
  render: function() {
    return <h1>Hello, {this.props.name}</h1>;
  }
});

ES6 extends的使用可使得继承意义更加明确:

class Greeting extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

而且值得一提的是,若是你使用extends来定义React的组件,那么能够在类的构造器里面,用简单的this.state =...的声明方式来替代getInitialState()方法。

Filter函数

好比咱们有如下的数组:

const numbers = [5,1, 20, 90, 8, 22, 33, 9]

若是想经过上面的数组来建立一个新的数组,而里面的值都是大于10的。在ES5的语法下,你可能须要一个for循环,或者一些类似的操做(好比: jQuery的each())。

如今,咱们有了ES6,就可使用filter函数来遍历数组中的全部值,而且留下那些知足条件的值。

//ES6

const notDigits = numbers.filter( function(value) {return value > 9})
console.log(notDigits) // 打印出 [20,90,22,33]

// 或者使用箭头函数:
const notDigits1 = numbers.filter( (value) =>  {return value > 9}
// 或者使用箭头函数默认返回的形式去掉return关键字:
const notDigits2 = numbers.filter( (value) => value > 9 )

Map函数

Map函数多是JavaScript最不被人重视的函数之一,即便它在ES5语法就有了。基本上,若是你须要遍历一个数组,你就可使用map函数。

好比咱们有跟上面例子同样的数组:

const numbers = [5,1, 20, 90, 8, 22, 33, 9]

若是想操做数组,就可使用map函数:

numbers.map( (n) => console.log(n))
// 还能够加第二个参数, index
numbers.map( (n, index) => console.log(n + ' is the ' + index + ' value from the array ') )
// 或者咱们想建立新的数组
const double= numbers.map( (n) => n*2 )

你将会在React中常常看到map(), 不少时候它会用来显示一个项目列表:

render() {
    return(
  this.props.items.map( (item, key) =>  <p key={key}>{item}</p>
  )
}

以上就是我在写React代码中使用最多的ES6特性,可能会有一些偏颇以及带有主观性,可是我绝没有贬低ES6其余新功能实用性的想法。如前所述,还有许多其余ES6在这里没有涉及,但这些概念容许你轻松地从ES5 React升级到新的ES6语法,并了解来自React以及来自新ES6功能的内容。Cheers and happy coding!

相关文章
相关标签/搜索