我可以在静态页面中将Axios与ReactJS一起使用吗?

时间:2017-07-01 17:33:17

标签: forms reactjs post request axios

我想为我的反应应用创建一个联系表单,这是一个静态应用程序(我根本没有后端,只有前端)。我正在尝试通过对某个API的POST请求来执行此操作,并且我发现Axios可能会有所帮助。我想做一些事情,比如用户单击“提交”按钮时,它会调用一个函数来执行表单上的所有验证,然后通过带有Axios的POST操作提交数据。

这是可能的,还是我的方法错了?提前谢谢。

1 个答案:

答案 0 :(得分:3)

是的,你可以。您要做的是侦听表单的onSubmit事件并在该侦听器中发送POST请求。您也可以在该方法中进行验证。

handleSubmit(e) {
  // Stop browser from submitting the form.
  e.preventDefault();

  // Validate here or directly when setting state.
  // ...

  // Then send a POST request to your endpoint.
  axios
    .post('https://your-form.com/endpoint', {
      // Your data goes here.
      firstName: this.state.firstName,
      lastName: this.state.lastName
    })
    .then(function(response) {
      // Done!
      console.log(response);
    })
}

// In the render method: listen for the submit event.
<form onSubmit={this.handleSubmit} />

这是一个有效的例子:

&#13;
&#13;
class Example extends React.Component {
  constructor() {
    super();
    this.state = {
      firstName: '',
      lastName: ''
    };

    this.handleSubmit = this.handleSubmit.bind(this);
    this.handleChange = this.handleChange.bind(this);
  }

  handleSubmit(e) {
    // Stop browser from submitting the form.
    e.preventDefault();

    // Validate here or directly when setting state.
    // Then send a POST request to your endpoint.
    axios
      .post('https://reqres.in/api/users', {
        firstName: this.state.firstName,
        lastName: this.state.lastName
      })
      .then(function(response) {
        console.log(response);
      })
      .catch(function(error) {
        console.log(error);
      });
  }

  handleChange(e) {
    this.setState({
      [e.target.name]: e.target.value
    });
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <input
          type="text"
          name="firstName"
          value={this.state.firstName}
          onChange={this.handleChange}
        />
        <input
          type="text"
          name="lastName"
          value={this.state.lastName}
          onChange={this.handleChange}
        />
        <input type="submit" />
      </form>
    );
  }
}

ReactDOM.render(<Example />, document.getElementById('root'));
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.16.2/axios.min.js"></script>

<div id="root"></div>
&#13;
&#13;
&#13;