如何遍历axios响应

4

我有一个API调用,将响应设置在状态中,如下:

componentDidMount(){
    var a=this;
    axios.post("http://localhost/axios/index.php")
    .then((res)=>{
          console.log(res.data);
          a.setState(
            { datas:res.data },
            () => console.log(this.state.datas)
          );
    });
}

我遇到了

{0: {…}, 1: {…}, 2: {…}, 3: {…}, 4: {…}, 5: {…}}
0: {id: "1", typee: "class", user_id: "1"}
1: {id: "2", typee: "class", user_id: "1"}
2: {id: "3", typee: "course", user_id: "1"}
3: {id: "4", typee: "class", user_id: "2"}
4: {id: "5", typee: "test_series", user_id: "3"}
5: {id: "6", typee: "test_series", user_id: "2"}

在状态中。我希望以表格格式显示这些数据,因此尝试了

render(){
return(
  <table>
    <thead>
      <tr>
        <th>S.No.</th>
        <th>Type</th>
      </tr>
    </thead>
    <tbody>
      {
        this.state.datas.map(data=>(
          <tr key={data.id}>
            <td>{data.id}</td>
            <td>{data.typee}</td>
          </tr>
        ))
      }
    </tbody>
  </table>
)
}

但它给了我this.state.datas.map不是一个函数的错误提示。我已将我的数据状态初始化为空数组。

1个回答

2

这是因为res.data是一个对象,而不是一个数组。我想你可以在将其赋值给state之前将其转换为对象数组。

只需使用ES6中提供的Object.values()方法即可创建一个数组,该数组使用对象中所有键值对的值。

componentDidMount(){
    var a=this;
    axios.post("http://localhost/axios/index.php")
    .then((res)=>{
          a.setState(
            { datas: Object.values(res.data) },
            () => console.log(this.state.datas)
          );
    });
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接