【问题标题】:TypeError: Cannot read property 'map' of undefined-React errorTypeError:无法读取未定义反应错误的属性“地图”
【发布时间】:2019-11-17 18:43:29
【问题描述】:

我正在使用 axios 从用户列表的数据库中获取数据。我已经安装了 axios 来发送数据,它工作正常,在获取数据时我收到错误:“无法读取未定义的属性 'map'”

下面是我的users.js代码

export default class users extends Component {
    constructor(props) {
        super(props);
        this.state = {
            Users: []
        };
    }
    getUsersData() {
        axios
            .get(`http://localhost:8080/users-react/api/contact/users.php`, {})
            .then(res => {
                const data = res.data
                console.log(data)
                const users = data.map(u =>
                    <div>
                     <p>{u.name}</p>
                    <p>{u.email}</p>
                    </div>
                    )
                    this.setState({users})})
            .catch((error) => {
                console.log(error)
            })
   }
    componentDidMount(){
        this.getUsersData()
    }
    render() {
        return (
            <div>
                {this.state.users}
            </div>
        )
    }
}

请告诉我我犯了什么错误,我是 React 新手

【问题讨论】:

  • 您在控制台上通过console.log(data) 得到了什么?为什么将空对象传递给axios.get()
  • 在控制台获取数据。映射 undef 错误
  • this放在axios之前,例如this.axios
  • 现在出现这个错误“Cannot read property 'get' of undefined”
  • 在控制台获取 data.map 之前不是函数

标签: reactjs react-redux


【解决方案1】:

更改地图功能的代码,现在可以正常工作了:

posts.map(post => {
              const { user_id, name, email } = post;
              return (
                <div key={user_id}>
                  <h2>{name}</h2>
                  <p>{email}</p>
                  <hr />
                </div>
              );
        })

【讨论】:

    猜你喜欢
    • 2021-12-02
    • 2020-09-23
    • 1970-01-01
    • 1970-01-01
    • 2021-08-28
    • 2021-02-01
    • 2020-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多