简体   繁体   English

我如何在反应中显示后端响应?

[英]How can i Show Back-End response in react?

How can I show the response of the following request?如何显示以下请求的响应?

function Submit(e) {
    e.preventDefault();
    axios
      .post(url, {
        email: data.email,
        password: data.password,
        confirmpassword: data.confirmpassword,
        first_name: data.first_name,
        last_name: data.last_name,
        mobile: data.mobile,
        birthday: data.birthday,
        gender: data.gender,
        profession: data.profession,
      })
      .then((res) => {
        console.log(res.data);
      });
  }

Use the 'state' hook to hold your data.使用“状态”挂钩来保存您的数据。 When it gets updated, it automatically updates the clients state (screen/gui).更新后,它会自动更新客户端 state(屏幕/图形用户界面)。

If you want to run the code as soon as the page loads, use it in an effect hook.如果您想在页面加载后立即运行代码,请在效果挂钩中使用它。

import React, { useEffect, useState } from 'react';

export default function YourComponent() {

  const [yourObject, setYourObject] = useState({});

//optional
 useEffect({
    getData(null);
 },[]);
 
  function getData(e) {
    if(e)
      e.preventDefault();

    axios.post(url,
      {
        email: data.email,
        password: data.password,
        confirmpassword: data.confirmpassword,
        first_name: data.first_name,
        last_name: data.last_name,
        mobile: data.mobile,
        birthday: data.birthday,
        gender: data.gender,
        profession: data.profession,
      })
      .then((res) => {
        setYourObject(res.data)
      });
  }

  return (
   <div>
     <button onClick={e=>getData(e)}>
        Get Data
     </button>
    {if(Object.keys(yourObject).length > 0) &&
      <h1>First Name: </h1><p>{yourObject.first_name}</p>
      <h1>Last Name: </h1><p>{yourObject.last_name}</p>
      <h1>Birthday: </h1><p>{yourObject.birthday}</p>
      {/* ...etc. */}
    }
   </div>
  )
}

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

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