React Js setState

时间:2017-06-19 10:21:21

标签: reactjs

我陷入了setState。我提交表单并通过ajax调用发送数据。作为回报,我获取响应数据并希望将值存储在setState中并在UI中打印。但是我无法正确存储它。我无法理解我哪里出错了。

以下是代码:

class NameForm extends React.Component {
  constructor(props) {
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.state = {
      res : "",
      month : "",
      day : "",
      year : ""
    }
  }

  handleSubmit(event) {
    event.preventDefault();
    var name = this.input.value;
    var parent = this;

    $.ajax({
      url: '/url',
      dataType: 'json',
      type: 'POST',
      data: {
          month: this.state.month,
          day: this.state.day,
          year: this.state.year
      },
      success: function(data) {
          console.log(data) // Here I'm getting correct response.. 
          parent.setState({res: data.res});
      }.bind(this),
    });
  }

  render() {
    return (
      <div>
        <form onSubmit={this.handleSubmit}>
          <label>
            Name:
            <input type="text" ref={(input) => this.input = input} />
          </label>
          <input type="submit" value="Submit" />
        </form>

        <div id="res">
            {this.state.res} // The value is not printing here.. 
        </div>

      </div>
    )
  }
}

0 个答案:

没有答案