通知何时设置了React状态?

时间:2017-01-23 06:25:44

标签: ajax forms reactjs

我们无法想到这样做的方法:我有一个表单,并在提交时使用输入发出ajax请求,但是如何在发出请求之前确保状态已完全设置?我知道setState是异步的,并且存在接受回调的版本,但是我不想在设置状态时立即提交,而是在用户单击提交按钮时提交。当我发出请求时,this.state仍为null。

任何帮助或提示将不胜感激,谢谢!

import React from 'react';

export default class Landing extends React.Component {
  constructor(props) {
    super(props);

    this.handleClick = this.handleClick.bind(this);
    this.handleChange = this.handleChange.bind(this);
    this.state = {
      question: ""
    };
  }

  handleClick(e) {
    const xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
      if (xhttp.readyState === XMLHttpRequest.DONE) {
        if (xhttp.status === 200) {
          console.log("success")
        } else {
          alert('There was a problem with the request.');
        }
      }
    };
    xhttp.open('POST', '/save', true);
    xhttp.setRequestHeader("Content-Type", "application/json");
    xhttp.send(JSON.stringify({ question: this.state.question }));
  }

  handleChange(e) {
    this.setState({ question: e.target.value });
  }

  render() {
    return (
      <div className="landing">
        <form onSubmit={this.handleClick}>
          <label>
            Question:
            <input type="text" value={this.state.question} onChange={this.handleChange} />
          </label>
          <input type="submit" value="Submit" />
        </form>    
      </div>
    );
  }
}

1 个答案:

答案 0 :(得分:1)

你试过这个吗?

  this.setState({
        state : newState
    },
    () => {
       // Call some method when state changes were done.
    });

此外,您应该使用e.preventDefault();,因为您没有将for提交给任何服务器。

  handleClick(e) {

   e.preventDefault();
    const xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
      if (xhttp.readyState === XMLHttpRequest.DONE) {
        if (xhttp.status === 200) {
          console.log("success")
        } else {
          alert('There was a problem with the request.');
        }
      }
    };
    xhttp.open('POST', '/save', true);
    xhttp.setRequestHeader("Content-Type", "application/json");
    xhttp.send(JSON.stringify({ question: this.state.question }));
  }