简体   繁体   English

如何在反应中使用 axios (post)

[英]how to use axios (post) in react

In react application i want to submit input field value to database using axios/post method,since i am new to react i don't have any clear idea.在反应应用程序中,我想使用 axios/post 方法将输入字段值提交到数据库,因为我是反应的新手,所以我没有任何明确的想法。 can anyone help me with examples?谁能帮我举个例子? Thanks in advance提前致谢

i tried following program我试过以下程序

import React, { Component } from 'react';
import axios from 'axios';

var panelStyle = {
    'max-width': '80%',
    margin: '0 auto'
}

class Register extends Component {
  constructor() {
   super();

    this.state = {
      formFields: {username: ''}
    }
  }

  render() {
    return(
     <div>
    <div class="panel panel-primary" style={panelStyle}>
      <div class="panel panel-heading">React Forum - Register</div>
      <div class="panel panel-body">
        <form onsubmit={this.formHandler(this.state.formFields)}>
          <strong>Username:</strong> <br /> <input type="text" name="username" placeholder="Nathaniel" onChange={(e) => this.inputChangeHandler.call(this, e)} value={this.state.formFields.username} /> <br />
          <strong>Email:</strong> <br /> <input type="email" name="email" placeholder="me@example.com" /> <br />
          <strong>Confirm Email:</strong> <br /> <input type="email" name="confirmemail" placeholder="me@example.com" /> <br />
          <strong>Password:</strong> <br /> <input type="password" name="password" placeholder="********" /> <br />
          <strong>Confirm Password:</strong> <br /> <input type="password" name="confirmpassword" placeholder="********" /> <br /><br />
          <button class="btn btn-primary">Register Account</button>
        </form>
      </div>
    </div>
  </div>

    );
  }

  inputChangeHandler(e) {
   let formFields = {...this.state.formFields};
   formFields[e.target.name] = e.target.value;
   this.setState({
    formFields
   });
  }

  formHandler(formFields) {
   axios.post('/api/register', formFields)
     .then(function(response){
       console.log(response);
       //Perform action based on response
   })
     .catch(function(error){
       console.log(error);
       //Perform action based on error
     });
  }
}

export default Register

and got following error in console并在控制台中出现以下错误

index.js:2178 Warning: The tag <children> is unrecognized in this browser. If you meant to render a React component, start its name with an uppercase letter.

Use maxWidth instead max-width .使用maxWidth代替max-width Use onSubmit={(e) => this.formHandler(e, this.state.formFields)} instead this.formHandler(this.state.formFields) because we need variable e to prevent form request html使用onSubmit={(e) => this.formHandler(e, this.state.formFields)}代替this.formHandler(this.state.formFields)因为我们需要变量e来防止表单请求 html

Use

formHandler(e, formFields) {
        e.preventDefault();
}

instead inputChangeHandler(e) {}而是inputChangeHandler(e) {}

import React, { Component } from 'react';
import axios from 'axios';

var panelStyle = {
    maxWidth: '80%',
    margin: '0 auto'
}

Here the code can run.代码可以在这里运行。

class Register extends Component {
    constructor() {
        super();

        this.state = {
            formFields: {username: ''}
        }
    }

    render() {
        console.log(this.state)
        return(
            <div>
                <div className="panel panel-primary" style={panelStyle}>
                    <div className="panel panel-heading">React Forum - Register</div>
                    <div className="panel panel-body">
                        <form onSubmit={(e) => this.formHandler(e, this.state.formFields)}>
                            <strong>Username:</strong> <br /> <input type="text" name="username" placeholder="Nathaniel" onChange={(e) => this.inputChangeHandler.call(this, e)} value={this.state.formFields.username} /> <br />
                            <strong>Email:</strong> <br /> <input type="email" name="email" placeholder="me@example.com" onChange={(e) => this.inputChangeHandler.call(this, e)} value={this.state.formFields.email}/> <br />
                            <strong>Confirm Email:</strong> <br /> <input type="email" name="confirmemail" placeholder="me@example.com" onChange={(e) => this.inputChangeHandler.call(this, e)} value={this.state.formFields.confirmemail}/> <br />
                            <strong>Password:</strong> <br /> <input type="password" name="password" placeholder="********" onChange={(e) => this.inputChangeHandler.call(this, e)} value={this.state.formFields.password}/> <br />
                            <strong>Confirm Password:</strong> <br /> <input type="password" name="confirmpassword" placeholder="********" onChange={(e) => this.inputChangeHandler.call(this, e)} value={this.state.formFields.confirmpassword}/> <br /><br />
                            <button className="btn btn-primary">Register Account</button>
                        </form>
                    </div>
                </div>
            </div>

        );
    }

    inputChangeHandler(e) {
        let formFields = {...this.state.formFields};
        formFields[e.target.name] = e.target.value;
        this.setState({
            formFields
        });
    }

    formHandler(e, formFields) {
        e.preventDefault();
        axios.post('/api/register', formFields)
            .then(function(response){


                console.log(response);
                //Perform action based on response
            })
            .catch(function(error){


                console.log(error);
                //Perform action based on error
            });
    }
}

export default Register

This is how I would set it up using with create-react-app.这就是我将它与 create-react-app 一起使用的方式。 I am a fan of using async/await .我喜欢使用async/await The handleSubmit and handleChange functions will automatically get called with the event and it is easy to reference state from inside handleSubmit to get the data you want to send in the post request. handleSubmithandleChange函数将自动与事件一起调用,并且很容易从handleSubmit内部引用状态以获取要在发布请求中发送的数据。 Sometimes, there is no choice but to use a callback style function in the JSX - like (e) => this.whatever(e, this.state.whatever) , but if it is avoidable I like to avoid it.有时,别无选择,只能在 JSX 中使用回调样式函数 - 比如(e) => this.whatever(e, this.state.whatever) ,但如果可以避免,我喜欢避免它。 Unrelated, but you can pull username, email, etc off of the formFields state in render to save having to type out this.state a lot.无关,但您可以在渲染中从formFields状态中提取用户名、电子邮件等,以节省大量输入 this.state 的麻烦。

   import React, { Component } from 'react'
   import axios from 'axios'

    class Register extends Component {

      state = {
        formFields: { user: '', email: '' }
      }  

      handleSubmit = async e => {
        e.preventDefault()
        const { formFields } = this.state
        try {
          let response = await axios.post('/api/register', formFields)
          // handle response
        } catch (error) {
          // handle error
        }

      }

      handleChange = e => {
        const { formFields } = this.state
        formFields[e.target.name] = e.target.value
        this.setState({ formFields })
      }

      render() {
        const { username, email } = this.state.formFields
        return () {
          <div>
            <form onSubmit={this.handleSubmit}>
               <strong>Username:</strong> <br /> <input type="text" name="username" placeholder="Nathaniel" onChange={this.handleChange} value={username} /> <br />
               <strong>Email:</strong> <br /> <input type="email" name="email" placeholder="me@example.com" onChange={this.handleChange} value={email}/> <br />
            <button>Register Account</button>
            </form>
          </div>
        }
      }
    }

export default Register

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM