【问题标题】:Axios POST res.data is undefinedAxios POST res.data 未定义
【发布时间】:2021-07-31 20:14:18
【问题描述】:

我有一个调用axios.post 的函数,该函数将对象返回给主反应应用程序,然后应将其保存/显示在屏幕上。

“postData”函数(在 API 中)的返回如下所示:

return axios.post(url, object).then((res) => res.data);

在主反应应用程序中,我有:

async postData (file1, file2, algorithm) {
   this.setState({
        anomalies: await api.postData(file1, file2, algorithm)
    }, () => { console.log(this.state.anomalies); }
    )
}

当我console.log 异常时(如代码中所示),我得到未定义。 另外,我有一个 div 为:

<div> {this.state.anomalies} <div/>

里面显示了相关的内容,但是调用之后什么都不显示。

如果我这样做:

axios.post(url, object).then((res) => console.log(res.data);

我得到了正确的打印对象。那么如何才能以正确的方式将这个对象传递给 React 应用呢?

谢谢!

【问题讨论】:

  • 在更新后立即记录状态将记录旧值,因为状态是异步更新的,并且状态在组件的特定渲染中是恒定的。要记录更新的状态,您可以使用 this.setState 的第二个可选参数,它是一个回调函数,在状态更新后调用。
  • 谢谢,我已经更改了代码(见编辑),但仍然打印了 undefined。

标签: reactjs post axios state


【解决方案1】:

App.js 文件

import React from "react";

import API from "./API";

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { anomalies: null };
  }

  post = async () => {
    this.setState(
      {
        anomalies: await API.postData()
      },
      () => {
        console.log(this.state.anomalies);
      }
    );
  };

  render() {
    return (
      <div>
        <button onClick={this.post}> click</button>
      </div>
    );
  }
}

API.js 文件

import axios from 'axios'


function postData () {
  return axios.get("https://jsonplaceholder.typicode.com/todos/1").then( res =>  res.data)
}


export default {
  postData
}

【讨论】:

    猜你喜欢
    • 2020-10-26
    • 2021-06-08
    • 1970-01-01
    • 1970-01-01
    • 2017-09-27
    • 2019-12-18
    • 1970-01-01
    • 2019-03-30
    • 2021-05-26
    相关资源
    最近更新 更多