为什么会出现此错误? users.map不是函数

时间:2020-09-01 19:43:19

标签: javascript reactjs react-native react-redux axios

我正在尝试解决此问题,我什至在同一个主题上阅读了40多个答案,但仍然找不到相关的解决方法。这就是为什么我要请我帮助解决这个问题。 我正在尝试使用axios从API呈现名称。即使我可以在控制台中看到所有数据,但由于显示错误 users.map不是函数而无法呈现 下面,我分享我的文件代码。 附言:我很新,这可能就是我无法弄清楚的原因。 请看一下我的代码。

import React from 'react';
import './App.css';
import 'bootstrap/dist/css/bootstrap.min.css'
import { Container, Table} from "react-bootstrap";
import axios from 'axios';

class App extends React.Component {
    state = {
        users: [],
    };

    componentDidMount () {
        axios.get('https://5w05g4ddb1.execute-api.ap-south-1.amazonaws.com/dev/profile/listAll')
            .then(response => {
                const users = response.data;
                this.setState({ users });
                console.log(this.state.users);
            })
    }

    render() {
        const { users } = this.state;
        return (
        <div className="App">
              <Container fluid>
                  <Table striped bordered hover size="sm">
                      <thead>
                      <tr>
                          <th><div id="">Image</div></th>
                          <th>Name</th>
                          <th>Gender</th>
                          <th>Age</th>
                          <th>Date</th>
                          <th>Status</th>
                      </tr>
                      </thead>
                      <tbody>

                      <tr>
                          { users.map(user => { return <td key={user.id}>{ user.name }</td> }) }

                      </tr>
                      </tbody>
                  </Table>
              </Container>
        </div>
      )
}
}

export default App;

4 个答案:

答案 0 :(得分:1)

在您的axios中,在“然后”部分中更改行:

const users = response.data;

收件人:

const users = response.data.list;

答案 1 :(得分:1)

您得到的响应不是数组,而是这样的对象:

{"list":[{"id":"MnJJA0dbuw","name":"Anand Sharma","img":"https://incablet-tests.s3.ap-south-1.amazonaws.com/conference-content/photos/sponsors/Anand.jpeg","gender":"m","age":46,"date":"23/11/2019","status":"onboarded"}]}

您可以通过将const users = response.data;替换为const users = response.data.list;来访问数组

答案 2 :(得分:0)

快速破解

{users.list.map(user => { return <td key={user.id}>{ user.name }</td> }) }

答案 3 :(得分:-1)

有2个错误:

  1. api的响应不是列表,而是对象,您需要转到response.list才能使用响应中的列表 应该是
const users = response.data.list
  1. 您的
this.setState({users})

,您需要将其更改为

this.setState({users:<VARIABLE_NAME_TO_HOLD_USER_DATA>}) 

即使您写的内容像在ES6中一样有效,这在某种程度上也是个坏主意,不清楚您在做什么,只需定义要复制到ur组件状态的内容