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

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

1.ES6 Arrow Functions

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

// Old way with ES5
componentDidMount: function() {
  userApi.getList().then(function(users) {
    this.setState({users: users});
  });
},

// New way with ES6 Arrow Functions
componentDidMount: 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 method
render: 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 method
render: 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 method
render: 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值