• React Ajax this.IsMounted() is not a function


    组件的数据来源,通常是通过 Ajax 请求从服务器获取,可以使用 componentDidMount 方法设置 Ajax 请求,等到请求成功,再用 this.setState 方法重新渲染 UI 

    var UserGist = React.createClass({
      getInitialState: function() {
        return {
          username: '',
          lastGistUrl: ''
        };
      },
    
      componentDidMount: function() {
        $.get(this.props.source, function(result) {
          var lastGist = result[0];
          if (this.isMounted()) {
            this.setState({
              username: lastGist.owner.login,
              lastGistUrl: lastGist.html_url
            });
          }
        }.bind(this));
      },
    
      render: function() {
        return (
          <div>
            {this.state.username}'s last gist is
            <a href={this.state.lastGistUrl}>here</a>.
          </div>
        );
      }
    });
    
    ReactDOM.render(
      <UserGist source="https://api.github.com/users/octocat/gists" />,
      document.body
    );

     然后浏览器报了这样一个错

     this.IsMounted() is not a function

    对比了一下React中文api和阮一峰大神的demo,确实都是这样写的。为啥会错?

    随即去翻了React官网的API,原来 isMounted() 这个方法被React废弃掉了,so 不能用这个函数了

    然后官网给了一个案例

    var UserGist = React.createClass({
      getInitialState: function() {
        return {
          username: '',
          lastGistUrl: ''
        };
      },
     
      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();
      },
     
      render: function() {
        return (
          <div>
            {this.state.username} 用户最新的 Gist 共享地址:
            <a href={this.state.lastGistUrl}>{this.state.lastGistUrl}</a>
          </div>
        );
      }
    });
     
    ReactDOM.render(
      <UserGist source="https://api.github.com/users/octocat/gists" />,
      mountNode
    );

    官网是这么解释的

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

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

     componentWillUnmount()

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

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

    所以我们可以用这个方法替代 isMounted() 来确保该组件是否还是mounted

  • 相关阅读:
    1654. Minimum Jumps to Reach Home
    1129. Shortest Path with Alternating Colors
    1766. Tree of Coprimes
    1368. Minimum Cost to Make at Least One Valid Path in a Grid
    LeetCode 841 钥匙与房间
    LeetCode 268 缺失数字
    LeetCode 136 只出现一次的数字
    LeetCode 461 汉明距离
    LeetCode 557 反转字符串中的单词 III
    LeetCode 392 判断子序列
  • 原文地址:https://www.cnblogs.com/hjsblogs/p/6406121.html
Copyright © 2020-2023  润新知