zoukankan      html  css  js  c++  java
  • 解决React通过ajax加载数据更新页面不加判断会报错的问题

    通过AJAX加载数据是一个很普遍的场景。在React组件中如何通过AJAX请求来加载数据呢?首先,AJAX请求的源URL应该通过props传入;其次,最好在componentDidMount函数中加载数据。加载成功,将数据存储在state中后,通过调用setState来触发渲染更新界面。

    AJAX通常是一个异步请求,也就是说,即使componentDidMount函数调用完毕,数据也不会马上就获得,浏览器会在数据完全到达后才调用AJAX中所设定的回调函数,有时间差。因此可以使用 componentWillUnmount 来取消任何未完成的请求;

    componentDidMount: function() {
        this.serverRequest = $.get(this.props.source, function (result) {
          var lastGist = result[0];
          this.setState({
            username: lastGist.owner.login,
            lastGistUrl: lastGist.html_url
          });
        }.bind(this));
      },
     
      componentWillUnmount: function() {
        this.serverRequest.abort();
      }

    官网是这么解释的

    When fetching data asynchronously, use componentWillUnmount to cancel any outstanding requests before the component is unmounted.

    当异步加载数据的时候, 使用 componentWillUnmount 来取消任何未完成的请求 在组件卸载之前

     componentWillUnmount()

    在组件从 DOM 中移除的时候立刻被调用。

    在该方法中执行任何必要的清理,比如无效的定时器,或者清除在 componentDidMount 中创建的 DOM 元素

  • 相关阅读:
    BLOB
    cesium 检测视图改变的代码
    有关Nodejs的一些插件介绍
    线程基础知识
    进程和线程概念对比
    C#对象与XMl文件之间的相互转换(转)
    简介C#读取XML的方式(转)
    关于c# Debug和Release的区别 (转)
    c++堆和栈(转)
    浅谈C#堆栈与托管堆的工作方式(转)
  • 原文地址:https://www.cnblogs.com/Smiled/p/9317398.html
Copyright © 2011-2022 走看看