来自一个react SPA的总结--es6的应用

来源:互联网 发布:windows ce安装软件 编辑:程序博客网 时间:2024/06/06 02:19

这篇主要总结一些,es6在react中的应用,并没有囊括所有,只是总结一些本人平常没有理解的知识点………..

1.ES6 Arrow Functions

es6的箭头函数在这个简单project中用到多次,下面以一个对比代码块展示一下:

// Old way with ES5componentDidMount: function() {  userApi.getList().then(function(users) {    this.setState({users: users});  });},// New way with ES6 Arrow FunctionscomponentDidMount: function() {  userApi.getList().then(users => {    this.setState({users: users});  });}

注意参数的地方,如果原先函数中没有参数或者有多于一个参数,则不能省去()哦!使用箭头函数,可以避免各种this指向的问题,下一篇文章会有介绍哦。点击查看吧


2.ES6 Spread Operator

在这个project中,使用es6的解构赋值来给component传递参数,下面通过代码段来展示这种用法:

假设我们想从parent component传递一个对象给child component:

// Parent Component's render methodrender: function() {  const user = {    name: 'Brad',    occupation: 'Web Development',    state: 'Arizona'  };  return (<ChildComponent user={user} />);}

通过这种user={user}的方式传递数据,如果子组件想要获得name这个数据,就需要通过this.props.user.name的方式获取数据,看下面这种方式

// Parent Component's render methodrender: function() {  const user = {    name: 'Brad',    occupation: 'Web Development',    state: 'Arizona'  };  return (<ChildComponent name={user.name} occupation={user.occupation} state={user.state} />);}

这种方式,子组件想要获得name或全部数据,需要this.props.name,前提是要像这样name={user.name} occupation={user.occupation} state={user.state}哦,也是挺麻烦的,所以使用es6的特性之一,解构赋值方便了许多哦!看下面的代码块:

// Parent Component's render methodrender: function() {  const user = {    name: 'Brad',    occupation: 'Web Development',    state: 'Arizona'  };  return (<ChildComponent {...user} />);}

这样,子组件只需要this.props.name,this.props.occupation,this.props.state方式就能获得传递过来的数据了

更详细的请看react官方文档Spread Attributes

0 0