javascript - ES6/React "this"关键字与 ajax 从服务器获取数据(教程)

标签 javascript class reactjs this ecmascript-6

<分区>

我正在关注 React Beginner Tutorial我正在尝试将其翻译成 ES6。但是,当我将 CommentBox 更改为 ES6 类时,它开始给我一个 this.props.url is undefined 错误(在 AJAX 调用中loadCommentsFromServer)。我认为这与 ES6 如何绑定(bind) this 有关,但我对这门语言(也不是 React)不是很熟悉,所以我不确定。我看过 React 0.13 release notes并看到了这个:

React.createClass has a built-in magic feature that bound all methods to this automatically for you. This can be a little confusing for JavaScript developers that are not used to this feature in other classes, or it can be confusing when they move from React to other classes.

我不太确定,但我认为这意味着我必须保存 this 的值(如 let that = this.bind(that) ) 但这也给出了相同的 this.props.url is undefined - 我不确定下一步要去哪里。

这是我当前的代码:

class CommentBox extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: []
    };
  }
  loadCommentsFromServer() {
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      cache: false,
      success: function(data) {
        this.setState({
          data: data
        })
      }.bind(this)
    });
  }
  handleCommentSubmit(comment) {
    var comments = this.state.data;
    var newComments = comments.concat([comment]);
    this.setState({ data: newComments });
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      type: 'POST',
      data: comment,
      success: function(data) {
        this.setState({ data: data });
      },
      error: function(xhr, status, err) {
        console.error(this.props.url, status, err.toString());
      }.bind(this)
    });
  }
  componentDidMount() {
    this.loadCommentsFromServer();
    setInterval(this.loadCommentsFromServer, this.props.pollInterval);
  }
  render() {
    return (
      <div className="commentBox">
        <h1>Comments</h1>
        <CommentList data={this.state.data}/>
        <CommentForm onCommentSubmit={this.handleCommentSubmit}/>
      </div>
    );
  }
};

最佳答案

您需要使用 bind(this) 来绑定(bind)您的事件。如下所示:

componentDidMount() {
    this.loadCommentsFromServer().bind(this);
    setInterval(this.loadCommentsFromServer.bind(this), this.props.pollInterval);
  }

您可以从此链接阅读引用资料: https://facebook.github.io/react/docs/reusable-components.html#no-autobinding

没有自动绑定(bind) 方法遵循与常规 ES6 类相同的语义,这意味着它们不会自动将 this 绑定(bind)到实例。您必须明确使用 .bind(this) 或箭头函数 =>。

关于javascript - ES6/React "this"关键字与 ajax 从服务器获取数据(教程),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32729875/

相关文章:

javascript - 表示 react-redux 连接组件的 UML 图

javascript - 如何从 blob url (URL.createObjectURL()) 创建 pdf 文件对象

javascript - react slider 组件

javascript - 在 Node js 中将异步函数转换为同步函数?

swift - 从另一个类创建对象时,对象不会生成

Python:获取方法所属的类

java - 在类中创建 HashMap ?

javascript - 光滑的图像变为 1px 高度

javascript - 当文本从输入中完全删除时执行某些操作

javascript - 如何用html php js打印身份证?