尝试制作Ajax请求并在React Componenet中使用响应

时间:2015-09-18 00:44:10

标签: javascript ajax node.js reactjs

我有一个tweet box component,其getAllTweets函数调用submit。句柄提交函数is supposed to capture the value of the field and pass it to the getAllTweets函数so it the URL, so I can make a dynamic Ajax request. I am unable to save the variable containing the handle`值并追加它。其次,当我得到响应时,我需要将它绑定到TweetList组件。我无法工作......

var Tweet = React.createClass({
  render: function() {
    var rawMarkup = marked(this.props.children.toString(), {sanitize: true});
    return (
      <div className="tweet">
        <h2 className="tweetAuthor">
          {this.props.handle}
        </h2>
        <span dangerouslySetInnerHTML={{__html: rawMarkup}} />
      </div>
    );
  }
});

var TweetBox = React.createClass({
  getAllTweets: function(handle) {
    var handle = this.state.data;
    $.ajax({
      url: this.props.url + handle,
      dataType: 'json',
      type: 'POST',
      data: tweet,
      success: function(data) {
        console.log(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: []};
  },
  render: function() {
    return (
      <div className="tweetBox">
        <h1>Tweets</h1>
        <TweetList data={this.state.data} />
        <TweetForm onTweetSubmit={this.getAllTweets} />
      </div>
    );
  }
});

var TweetList = React.createClass({
  render: function() {
    var tweetNodes = this.props.data.map(function(tweet, index) {
      return (
        <Tweet handle={tweet.handle} key={index}>
          {tweet.message}
        </Tweet>
      );
    });
    return (
      <div className="tweetList">
        {tweetNodes}
      </div>
    );
  }
});

var TweetForm = React.createClass({
  handleSubmit: function(e) {
    e.preventDefault();
    var handle = React.findDOMNode(this.refs.handle).value.trim();
    if (!handle) {
      return;
    }
    this.props.onTweetSubmit({handle: handle, message: message});
    React.findDOMNode(this.refs.handle).value = '';
  },
  render: function() {
    return (
      <form className="tweetForm" onSubmit={this.handleSubmit}>
        <input type="text" placeholder="Your name" ref="handle" />
        <input type="submit" value="Post" />
      </form>
    );
  }
});

React.render(
  <TweetBox url="http://localhost:4000/api/"/>,
  document.getElementById('content')
);

1 个答案:

答案 0 :(得分:0)

首先,您忘记在TweetForm组件中声明message变量。

  

this.props.onTweetSubmit({handle:handle,message:message});

getAllTweets函数中,您传入handle变量并再次创建另一个新的handle变量(var handle = this.state.data)。这就是为什么你不能得到推文帐户名。

不要在方法中对多个变量使用相同的名称。