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 插件来转换其成为浏览器支持的语法,虽然没有性能的提升,但对于代码编写体验要更好。

  • 相关阅读:
    远程桌面无法复制粘贴
    软件无法启动,不提示具体错误
    从数据库统计出某张表中某个字段重复次数
    程序员何去何从
    SQL Server中TRUNCATE 和 DELETE的区别
    关于C#自定义控件注释说明
    C#的winform程序下如何实现文本编辑框(TextBox)的Hint提示文字效果
    ubuntu固定内网ip地址
    数据库的优化处理 Memory cached
    MYSQL管理之主从同步管理
  • 原文地址:https://www.cnblogs.com/crazycode2/p/9806528.html
Copyright © 2011-2022 走看看