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

时间:2019-10-09 04:36:37

标签: javascript reactjs axios

我已经使用Axios发出了发布请求,并且可以在Devtools控制台中看到存储在数据对象中的响应。

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

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数组。 items数组为空,因此我无法使用map()遍历该数组。端点工作正常,我已经对其进行了测试。请帮我解决这个问题。

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

这可能应该起作用。

正如豹所说,做到这一点的一种方法是使用异步,因此这是有效的代码

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,
      })
    })

或改为使用箭头功能

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

bind this关键字

此外,如评论中所述,我不确定是否可以使用带有箭头的功能,说在代码中检查以下行(反正不必要)

function(json) => {