[英]Why does it return `Cannot read property 'map' of undefined` when I'm trying to connect backend with React?
I'm a beginner in React and I'm following this tutorial https://dev.to/kmaryam27/step-by-step-react-nodejs-and-mysql-simple-full-stack-application-2018-part-5-5a8c to connect my database with React in front end and display the data.我是 React 的初学者,我正在学习本教程https://dev.to/kmaryam27/step-by-step-react-nodejs-and-mysql-simple-full-stack-application-2018-part- 5-5a8c将我的数据库与前端的 React 连接并显示数据。 I kept getting
TypeError: Cannot read property 'map' of undefined
when running npm start
at localhost:3000
in express-react/backend/client/src in part 5. Here is my express-react/backend/client/src/App.js:我不断收到
TypeError: Cannot read property 'map' of undefined
when running npm start
at localhost:3000
in express-react/backend/client/src 在第 5 部分。这是我的 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;
I get Welcome to Express express at localhost:3001
when running npm start
in /express/backend, and if I run node server
as shown in tutorial part 3, I could see the database content in localhost:3000
.当在 /express/backend 中运行
npm start
,我在localhost:3001
收到 Welcome to Express express,如果我按照教程第 3 部分所示运行node server
,我可以在localhost:3000
中看到数据库内容。
If I place a debugger
above console.log(data.data.users);
如果我在
console.log(data.data.users);
上方放置一个debugger
; , I could see variable data
returns this: ,我可以看到变量
data
返回:
Could someone help please?有人可以帮忙吗?
data.data
looks to contain a string instead of an object with the expected users
key. data.data
看起来包含一个字符串,而不是带有预期users
密钥的 object。
You should make sure you reply within the backend with a valid JSON (currently, it's an HTML as string).您应该确保在后端使用有效的 JSON 进行回复(目前,它是一个 HTML 作为字符串)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.