这篇主要总结一些,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方式就能获得传递过来的数据了