javascript - 当我尝试将后端与 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 start
node server
localhost:3000
如果我放置 a debugger
above console.log(data.data.users);
,我可以看到变量data
返回:
有人可以帮忙吗?
解决方案
data.data
看起来包含字符串而不是具有预期users
键的对象。
您应该确保在后端使用有效的 JSON 进行回复(目前,它是一个 HTML 字符串)。
推荐阅读
- r - 在 R 中编码条件期望
- apache-pig - 如何获得 Apache pig 中两个 COUNT() 操作的差异?
- java - 无法在 Dialogflow 模拟器中显示响应。请改为在 Google Assistant 模拟器上进行测试
- r - R Studio:一次选择和计算多列
- java - Java8流collectors.ToMap方法引用失败
- javascript - window.close 不适用于 Twitter 网站
- python - 按多个对象分页django
- javascript - 节点 js 等待在 catch 块抛出错误中进行的异步调用
- python - 我正在尝试简单地制作一个脚本,该脚本将通过我的登录收集 cookie,然后将它们的名称打印出来
- java - 如何为许多听众中的任何一个对 UI 重复/重新加载代码进行任何更改?