解决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 元素

 

posted @ 2018-07-16 14:10  李文杨  阅读(1629)  评论(0编辑  收藏  举报