zoukankan      html  css  js  c++  java
  • React中的Ajax

    React中的Ajax

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

    var  UserGist = React.createClass({
        getInitialState(){
            return {
                username:'',
                lastGistUrl:''
            };
        },
        
        componentDidMount(){
            $.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(){
            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
    )
    

    上面代码使用jQuery完成了Ajax请求,这是为了便于说明。React本身没有任何依赖,完全可以不用jQuery,而使用其他库。

    我们甚至可以把一个Promise对象传入组件。

    ReactDOM.render(
        <RepoList promise={$.getJSON('https://api.github.com/search/repositories?q=javascript&sort=stars')} />,
        document.body
    )
    

    上面代码从Github的API抓取数据,然后将Promise对象作为属性,传给RepoList组件。

    如果Promise对象正在抓取数据(pending状态),组件显示“正在加载”;如果Promise对象报错(rejected状态),组件显示报错信息;如果Promise对象抓取数据成功(fulfilled状态),组件显示获取的数据。

    var RepoList = React.createClass({
      getInitialState: function() {
        return { loading: true, error: null, data: null};
      },
    
      componentDidMount() {
        this.props.promise.then(
          value => this.setState({loading: false, data: value}),
          error => this.setState({loading: false, error: error}));
      },
    
      render: function() {
        if (this.state.loading) {
          return <span>Loading...</span>;
        }
        else if (this.state.error !== null) {
          return <span>Error: {this.state.error.message}</span>;
        }
        else {
          var repos = this.state.data.items;
          var repoList = repos.map(function (repo) {
            return (
              <li>
                <a href={repo.html_url}>{repo.name}</a> ({repo.stargazers_count} stars) <br/> {repo.description}
              </li>
            );
          });
          return (
            <main>
              <h1>Most Popular JavaScript Projects in Github</h1>
              <ol>{repoList}</ol>
            </main>
          );
        }
      }
    });
    
    只研朱墨作春山
  • 相关阅读:
    Non Clustered Confluence: Database is being updated by another Confluence instance
    晦涩时光 浮光掠影
    迷雾重重 星光闪耀
    navicat 查询窗口快捷键
    sublime使用技巧记录
    mvn 手动打包并放置到本地仓库下
    git bash 风格调整(显示中文)
    windows控制台(console)乱码
    java调用第三方命令,process.waitfor()挂起(你不知道的坑)
    shell问题-报错即退出
  • 原文地址:https://www.cnblogs.com/guolintao/p/9019514.html
Copyright © 2011-2022 走看看