zoukankan      html  css  js  c++  java
  • async -- await 解决数据异步获取

    在React组件中,也比较一下 Promise 和 Async/Await 的方法异同。

    传统地使用 Promise :

    import React, { Component } from 'react'  
    import { connect } from 'react-redux'  
    import { createPost } from '../actions/post'
    
    class PostEditForm extends Component {  
      constructor(props) {
        super(props)
      }
    
      contributePost = e => {
        e.preventDefault()
    
        // .... get form values as params
    
        this.props.createPost(params)
        .then(response => {
          // show success message
        })
        .catch(err => {
          // show error tips
        })
      }
    
      render () {
        return (
          <form onSubmit={this.contributePost}>
            <input name="title"/>
            <textarea name="content"/>
            <button>Create</button>
          </form>
        )
      }
    }
    
    export default connect(null, dispatch => {  
      return {
        createPost: params => dispatch(createPost(params))
      }
    })(PostEditForm)
    

    如果使用 Async/Await :

    import React, { Component } from 'react'  
    import { connect } from 'react-redux'  
    import { createPost } from '../actions/post'
    
    class PostEditForm extends Component {  
      constructor(props) {
        super(props)
      }
    
      async contributePost = e => {
        e.preventDefault()
    
        // .... get form values as params
    
        try {
          const result = await this.props.createPost(params)
          // show success message
        } catch (err) {
          // show error tips
        }
      }
    
      render () {
        return (
          <form onSubmit={this.contributePost}>
            <input name="title"/>
            <textarea name="content"/>
            <button>Create</button>
          </form>
        )
      }
    }
    
    export default connect(null, dispatch => {  
      return {
        createPost: params => dispatch(createPost(params))
      }
    })(PostEditForm)
    

    可以见得,两种模式, AsyncAwait 的更加直观和简洁,是未来的趋势。但是目前,还需要利用babel的 transform-async-to-module-method 插件来转换其成为浏览器支持的语法,虽然没有性能的提升,但对于代码编写体验要更好。

  • 相关阅读:
    使用signalr不使用连接服务器和前台的js的方法
    signalR client属性中的大致方法
    创建一个简单的signalr项目
    设计模式之工厂模式
    VS2012下没有ADO.NET实体数据模型
    迷你极客主机Station M1 开箱体验
    制作Station M1主机的Armbian启动卡
    StationP1的Ubuntu上安装gedit
    Station OS播放网络共享文件夹的媒体资源
    体验StationOS的推荐应用功能
  • 原文地址:https://www.cnblogs.com/crazycode2/p/9806528.html
Copyright © 2011-2022 走看看