首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何让组件/app等待ajax调用

如何让组件/app等待ajax调用
EN

Stack Overflow用户
提问于 2015-10-27 05:20:48
回答 1查看 275关注 0票数 0

我正在尝试找到最好的方法,让我的应用程序和组件依赖于我正在进行的单个ajax调用。我的应用程序通过第三方认证,为了真正向用户显示任何有意义的信息,我必须使用他们登录时的信息,然后调用另一个服务来获取有关他们的详细信息。到目前为止,我已经从几个示例中得出了以下结论

代码语言:javascript
复制
//auth.js
module.exports = {
  login(cb) {
    if (this.user) {
      if (cb) cb(true)
      this.onChange(true)
      return;
    }
    //if we don't have info about the user we call the other service here
    request((res) => {
      if (res) {
        this.user = res
        if (cb) cb(true)
        this.onChange(true)
      } else {
        if (cb) cb(false)
        this.onChange(false)
      }
    })
  },

  getUser() {
    return this.user
  },

  logout(cb) {
    delete this.user
    if (cb) cb()
    this.onChange(false)
  },

  loggedIn() {
    return !!this.user
  },

  onChange() {}
}

然后在我的组件中,我到处都在做这件事,这看起来不是一个很好的模式。

代码语言:javascript
复制
import React from 'react';
import ReactDOM from 'react-dom';
import auth from './auth'

export class ProductList extends React.Component{

  constructor(props) {
      super(props);
      //subscribe to on change event from the auth class
      auth.onChange = this.updateAuth.bind(this)
      this.state = {results: []};
  }

  componentWillMount() {
    //call login. if already logged in this method just returns the current user
    auth.login();
  }

  getProducts() {
    if(this.state.loggedIn) {
      $.get(config.server.url + "/api/User/" + auth.getUser().Id + "/Products", function(result) {
        this.setState({
          results: result.data.products
        });
      }.bind(this));
    }
  }

  updateAuth(loggedIn) {
    this.setState({
      loggedIn: loggedIn
    });
    this.getProducts()
  }

  componentDidMount() {
    this.getProducts()
  }

  render() {
    return (
      <table>
        <tbody>
            {this.state.results.map(function(result) {
               return <ProductItem key={result.Id} data={result}/>;
            })}
        </tbody>
      </table>
    )
  }
};

ReactDOM.render(
  (<ProductList/>),
  document.getElementById('react-forms')
);

所以我基本上只是在我拥有的每个react组件中挂接了一个事件处理程序,并检查所有地方的相同属性,它看起来很脆弱。我想我正在寻找一种方法来告诉我'App‘,在我的组件生效之前,我正在等待一些事情发生。

EN

回答 1

Stack Overflow用户

发布于 2015-10-28 04:46:51

我建议您遵循react教程(https://facebook.github.io/react/docs/tutorial.html#fetching-from-the-server)中概述的结构。ajax调用是使用jquery ajax函数从顶级组件CommentBox发出的,然后通过props向下传递给其他组件CommentListCommentForm。下面的代码直接取自本教程。由于您使用的是es6,因此语法略有不同,但概念保持不变。

代码语言:javascript
复制
var CommentBox = React.createClass({
  loadCommentsFromServer: function() {
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      cache: false,
      success: function(data) {
        this.setState({data: data});
      }.bind(this),
      error: function(xhr, status, err) {
        console.error(this.props.url, status, err.toString());
      }.bind(this)
    });
  },
  getInitialState: function() {
    return {data: []};
  },
  componentDidMount: function() {
    this.loadCommentsFromServer();
    setInterval(this.loadCommentsFromServer, this.props.pollInterval);
  },
  render: function() {
    return (
      <div className="commentBox">
        <h1>Comments</h1>
        <CommentList data={this.state.data} />
        <CommentForm />
      </div>
    );
  }
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33355843

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档