如何使用api.post发送数据?

时间:2020-09-25 09:44:26

标签: reactjs api backend

我对ReactJ不太熟悉,所以我需要帮助。我正在为用户填写表格,然后按提交。在我的一个功能组件(正在运行)中,我可以将其发送到数据库,而类组件则不能。我没有弄错哪部分代码是:

// Some js file that is working
const InitForm = {
  name : '',
  email: '',
  phone: '',
  message: ''
}

function ContactUs({}) {
   const [Form, setForm] = useState(InitForm);
   const {name, email, phone, message} = Form
   await api.post(`/contactus/createContactForm`, {data: Form});
}

//Another js file that is not working
class ContactUsDetails extends Component {
    constructor(props){
        super(props)
        this.state = {
            name: '',
            email: '',
            phone: '',
            message: ''
        }
    }

    await api.post(`/contactus/createContactForm`, {data: this.state});
}

2 个答案:

答案 0 :(得分:0)

请通过将API调用包装在生命周期方法之一中进行尝试。在您当前的代码中,永远不会调用它。

class ContactUsDetails extends Component {
  constructor(props){
    super(props)
    this.state = {
      name: '',
      email: '',
      phone: '',
      message: ''
    }

    api.post(`/contactus/createContactForm`, {data: this.state});
  }
}

答案 1 :(得分:0)

您需要使函数异步。使其async function ContactUs({}) { ...

您还如何调用该方法?

相关问题