【问题标题】:Capturing Json response for POST call to a api using axion in react [duplicate]在反应中使用axios捕获对api的POST调用的Json响应[重复]
【发布时间】:2019-12-19 14:28:48
【问题描述】:

我的任务是在 reactjs UI onclick 中对 API 进行 POST 调用。我相信,在 POST 调用之后,API 应该会发送一系列 JSON 对象。我正在尝试在 JSON 数组中捕获这些 JSON 对象。我是相当新的反应和轴心任何帮助将不胜感激。

我已从我的 UI 向虚拟 api 发出后调用,以检查 chrome 控制台上的响应。目前我在使用实际 API 时遇到了一些问题。但我正试图提前了解如何保存来自 API 的 JSON 响应。

import React from 'react';
import './App.css';
import axios from 'axios';



class App extends React.Component{
  obj = {
    "name": "abc",
    "Street":"Legacy",
    "City":"Plano",
    "State":"Texas",
    "ZIP":75024
  };
  constructor(){
    super()
    this.state = {
      address:[]
    }
    this.handleClick=this.handleClick.bind(this)
  }


  handleClick(){
    axios.post('https://jsonplaceholder.typicode.com/posts', {
      title: 'foo',
      body: 'bar',
      userId: 1
    })
    .then((response) => {
      console.log(response);
    }, (error) => {
      console.log(error);
    });
    console.log("I am working to Validate")
  }

在我实际的 reactJS 项目中,我将发送我目前在 POST 调用中硬编码为 obj 的 JSON 对象。我将在我想在地址中捕获的响应中接收 JSON 对象:[]

【问题讨论】:

  • 另一个重复的候选人:How to set state of response from axios in react
  • JavaScript !== JSON。 JSON 是有效 JavaScript 子集中数据的字符串表示形式。您使用的只是对象文字。您的 API 调用的有效负载和响应可能会在某些时候转换为 JSON,但这在这里无关紧要,因为您在任何时候都不必处理原始 JSON。
  • 捕获状态数据很简单,把这个写在你的.thenthis.setState({address:response.data})
  • 抱歉。我对软件工程相当陌生,对 javascript 或任何它的库和框架一无所知。我还在学习网络开发的术语。

标签: javascript reactjs axios


【解决方案1】:
 class App extends React.Component{

      constructor(){
        super();
        this.state = {
          address:[]
        }
        this.handleClick=this.handleClick.bind(this)
      }


      handleClick(){
            const obj = {
            name: "abc",
            Street:"Legacy",
            City:"Plano",
            State:"Texas",
            ZIP:75024
        };

        axios.post('https://jsonplaceholder.typicode.com/posts', obj)
        .then((response) => {
          console.log(response);

          if (response.data != null) {
              const data = response.data;
              this.setState({
                            address: data
                        });
          }

        })
        .catch(error => {
              console.log(error.data);
            });
      }

从 API 返回一个 "JsonResult" 对象,然后你可以在 React 中使用 "this.setState()" 方法将返回的 "JsonResult" 设置为 "address"。

【讨论】:

    猜你喜欢
    • 2021-03-24
    • 2020-08-01
    • 2017-11-28
    • 1970-01-01
    • 2021-01-06
    • 2019-01-04
    • 2020-08-22
    • 1970-01-01
    • 2019-10-02
    相关资源
    最近更新 更多