React native 之ES6语法(promise,箭头函数)

xiaoxiao2021-02-28  15

这里总结几个ES6与ES5区别中常用的几块。

一、箭头函数

ES6中提供了使用(=>)符号来定义函数。 箭头函数是用箭头符号在需要回调函数的地方之间定义不需要名称,代码简洁。 将需要的参数放在=>前的()中即可,=>后就是函数体,就可以使用传入的参数。 如:

var function = ()=>...;//这个是不需要参数的情况下 var function = (param) => param...;//一个参数的情况下, var function =(param1,param2)=>param1+param2;//参数多于一个的时候的情况

在实际开发中如:

...... myFunction(text){ //拿到textinput输入的值做处理 } render(){ return( <TextInput ... onChangeText = { (text) =>this.myFunction(text) } /> ); } ......

上面这种写法onChangeText = { (text) =>this.myFunction(text)}还可以改为 onChangeText = { this.myFunction},这种写法参数也可以传递,就是我们无法从代码看出参数的传递,实际也是传递过来了。但是不能写成onChangeText ={this.myFunction(text)},这样写就是错的。

二、map使用

示例:

var dataMap = [1,2,3,4]; var arr = dataMap.map( (item) =>{ return item*item; } );//生成的arr是[1,4,9,16]

三、promise机制

一个promise代表着一个异步任务的结果,异步任务结束后一般我们都会写有回调函数,来看任务是成功还是失败。promise机制就是让这个处理更简单。 如我们总常用的网络请求, 看下官网的示例:

fetch('https://mywebsite.com/endpoint.php') .then((response) => response.text()) .then((responseText) => { console.log(responseText); }) .catch((error) => { console.warn(error); });

在promise没推出前我们可能是这样写一个异步处理:

onSuccess(){ //操作成功 } onFailed(){ //操作失败 } try{ this.myFunction(param,this.onSuccess,this.onFailed)//onSuccess、onfailed是写的两个回调方法 }catch(error){ ...... }

promise推出后上面的代码就可以改成:

this.myFunction(param).then( (response)=>{ //response是成功返回的值 }).catch(error)=>{ //失败或者出现异常返回的结果,在这个地方处理 } )

promise还可以实现多重的连接,如上面官方网络请求的示例就是。

转载请注明原文地址: https://www.6miu.com/read-1900087.html

最新回复(0)