首页 > 解决方案 > 当我尝试将后端与 React 连接时,为什么它会返回“无法读取未定义的属性“地图”?

问题描述

我是 React 的初学者,我正在学习本教程https://dev.to/kmaryam27/step-by-step-react-nodejs-and-mysql-simple-full-stack-application-2018-part- 5-5a8c将我的数据库与前端的 React 连接并显示数据。TypeError: Cannot read property 'map' of undefined在第 5 部分中在 express-react/backend/client/src 中运行npm start时,我一直在运行localhost:3000。这是我的 express-react/backend/client/src/App.js:

import React, { Component } from 'react';
import axios from 'axios';
import './App.css';

class App extends Component {
  state = {
    users:[]
  }
  componentDidMount(){
    this.getUsers();
  }

  getUsers = _ => {
        axios.get('/')
    .then((data) => {
      console.log(data.data.users);
      this.setState({users: data.data.users});
    })
    .catch(error => console.log(error));
  }
  showUsers = user => <div key={user.id}>{user.username}</div>
  render() {
    const { users } = this.state;
    return (
      <div className="App">
        {users.map(this.showUsers)}
      </div>
    );
  }
}

export default App;

在 /express/backend 中localhost:3001运行时,我会收到 Welcome to Express express ,如果我按照教程第 3 部分所示运行,我可以在.npm startnode serverlocalhost:3000

如果我放置 a debuggerabove console.log(data.data.users);,我可以看到变量data返回: 在此处输入图像描述

有人可以帮忙吗?

标签: javascriptnode.jsreactjs

解决方案


data.data看起来包含字符串而不是具有预期users键的对象。

您应该确保在后端使用有效的 JSON 进行回复(目前,它是一个 HTML 字符串)。


推荐阅读