繁体   English   中英

如何以表格形式获取 axios 发布请求响应

[英]How to fetch axios post request response as a table

我使用Axios发出了一个发布请求,我可以在我的 Devtools 控制台中看到存储在数据 object 中的响应。

我尝试使用map function 对其进行迭代。 但是由于某种原因,该数组为空。

Axios POST 请求:-

axios.post('http://localhost:8080/accountStatus', {
      username : "username",
      accountStatus : "status"
    })
    .then(function(response) {
      console.log(response);
    })
    .catch(function(error) {
      console.log(error);
    });

items 数组已在我的构造函数中初始化。 渲染方法:-

var {items, username, accountStatus} = this.state;
<div className="App">
          <table>
          <thead>
               <td>
                {items.map(item =>
                  <tbody>
                    {item.username}
                  </tbody>
                )}
              </td>  
          </thead>
          </table>
</div>

错误是项目数组未定义。 items 数组是空的,因此我无法使用 map() 遍历数组。 端点工作正常,我已经测试过了。 请帮我解决这个问题。

您也可以像这样尝试此异步代码

async componentDidMount(){
   const items = await axios.post('http://localhost:8080/accountStatus',{username : "username",
  accountStatus : "status"}
  this.setState({isLoaded:true,items});
}

这应该可以工作。

正如黑豹所说,一种方法是使用异步,所以这是一个有效的代码

async componentDidMount(){
   const items = await axios.post('http://localhost:8080/accountStatus',{username : "username",
  accountStatus : "status"}
  this.setState({isLoaded:true,items});
}

在 Nane 代码/评论中,您提到了

TypeError:无法读取未定义的属性“setState”

为此,您可以做这两件事中的任何一件

const that = this
axios.post('http://localhost:8080/accountStatus', {
      username : "username",
      accountStatus : "status"
    })
    .then(function(response) {
        that.setState({
        isLoaded: true,
        items: response,
      })
    })

或使用箭头 function 代替

axios.post('http://localhost:8080/accountStatus', {
      username : "username",
      accountStatus : "status"
    })
    .then((response) => {
        that.setState({
        isLoaded: true,
        items: response,
      })
    })

或者bind this关键字

另外,正如评论中提到的,我不确定你是否可以使用 function 和箭头,说在你的代码中查看以下行(这无论如何都是不必要的)

function(json) => {

暂无
暂无

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

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