英文:
React js - Uncaught TypeError: records.map is not a function
问题
I'm working on a personal project using MERN Stacks, and I really can't prevent this error when trying to load Mongodb data
Uncaught TypeError: records.map is not a function
I'm trying to display data that is in the database into my view that'll display then in the admin interface. This is how the full view's code looks like:
import { useEffect, useState } from 'react'
import '../adminInterface.css'
import RecordList from './recordList'
const Productsadmin = () => {
const [records, setData] = useState(null)
useEffect(() => {
const fetchdata = async () => {
const data = await fetch('http://localhost:5000/api/getproducts/')
const json = await data.json()
if (data.ok) {
setData(json)
}
}
fetchdata()
}, [])
return (
<div className='main-page'>
<img className='logo-admin' src='https://i.imgur.com/v10SbL4.png'></img>
<div className='productsdata'>
{records && records.map((record) => (
<RecordList key={record._id} record={record} />
))}
</div>
</div>
)
}
export default Productsadmin
And here's the recordlist.js code:
const RecordList = ({ record }) => {
return (
<div className="record-details">
<h4>{record.productName}</h4>
<p><strong>Location : </strong>{record.location}</p>
<p><strong>Photo : </strong>{record.photo}</p>
</div>
)
}
export default RecordList
Also, I've tried to log the data before trying to render it, and it works perfectly.
英文:
I'm working on a personal project using MERN Stacks, and I really can't prevent this error when trying to load Mongodb data
Uncaught TypeError: records.map is not a function
I'm trying to display data that is in the the database into my view that'll display then in the admin interface this is how the full view's code look like:
import { useEffect , useState } from 'react'
import '../adminInterface.css'
import RecordList from './recordList'
const Productsadmin = () => {
const [records, setData] = useState(null)
useEffect(() => {
const fetchdata = async () => {
const data = await fetch('http://localhost:5000/api/getproducts/')
const json = await data.json()
if (data.ok) {
setData(json)
}
}
fetchdata()
},[])
return (
<div className='main-page'>
<img className='logo-admin' src='https://i.imgur.com/v10SbL4.png'></img>
<div className='productsdata'>
{records && records.map((record) => (
<RecordList key={record._id} record={record} />
))}
</div>
</div>
)
}
export default Productsadmin
and here's the recordlist.js code
const RecordList = ({ record }) => {
return (
<div className="record-details">
<h4>{record.productName}</h4>
<p><strong>Location : </strong>{record.location}</p>
<p><strong>Photo : </strong>{record.photo}</p>
</div>
)
}
export default RecordList
also I've tried to log the data before trying to render it, and it works perfectlly
答案1
得分: 1
为了使其正常工作,您应该将您的 records 变量初始化为空数组,这样您就可以在其上使用 map() 方法:
import { useEffect, useState } from 'react'
import '../adminInterface.css'
import RecordList from './recordList'
const Productsadmin = () => {
const [records, setData] = useState([]) // 初始化为空数组
useEffect(() => {
const fetchdata = async () => {
const data = await fetch('http://localhost:5000/api/getproducts/')
const json = await data.json()
if (data.ok) {
setData(json)
}
}
fetchdata()
}, [])
return (
<div className='main-page'>
<img className='logo-admin' src='https://i.imgur.com/v10SbL4.png'></img>
<div className='productsdata'>
{records.map((record) => (
<RecordList key={record._id} record={record} />
))}
</div>
</div>
)
}
export default Productsadmin
英文:
In order to work correctly, you should initialize your records variable to an empty array, so that you could then use the map() method on it :
import { useEffect, useState } from 'react'
import '../adminInterface.css'
import RecordList from './recordList'
const Productsadmin = () => {
const [records, setData] = useState([]) // Initialize to an empty array
useEffect(() => {
const fetchdata = async () => {
const data = await fetch('http://localhost:5000/api/getproducts/')
const json = await data.json()
if (data.ok) {
setData(json)
}
}
fetchdata()
}, [])
return (
<div className='main-page'>
<img className='logo-admin' src='https://i.imgur.com/v10SbL4.png'></img>
<div className='productsdata'>
{records.map((record) => (
<RecordList key={record._id} record={record} />
))}
</div>
</div>
)
}
export default Productsadmin
答案2
得分: 1
以下是您要翻译的内容:
"Your code中有两个错误。请检查此Expo Snack(用于RN,但逻辑相同):https://snack.expo.dev/@zvona/async-fetch
我会详细说明:
- 为了类型安全,使用一个空数组进行初始化:
const [records, setData] = useState([]);
- 用于处理JSON数据时,请确认它是数组,而不是对象:
setData(json);
}`
这两个问题在上面的示例中都得到了解决,具有正确的功能。"
<details>
<summary>英文:</summary>
There are two errors in your code. Please check this Expo Snack (for RN, but same logic): https://snack.expo.dev/@zvona/async-fetch
I'll elaborate:
1. for type safety, use an empty array for init: `const [records, setData] = useState([]);`
2. for handling JSON data, please confirm it's an *Array*, not an *Object*:
if (data.ok && Array.isArray(json)) {
setData(json);
}
Both of these are resolved in the example above with correct functionality.
</details>
# 答案3
**得分**: 0
需要将初始状态值设置为空数组,就像这样:
```jsx
const [records, setData] = useState([])
然后你可以运行你的代码。
如果数组为空,我也已经处理了错误,它会显示 "No Record message."。
import { useEffect, useState } from 'react'
import '../adminInterface.css'
import RecordList from './recordList'
const Productsadmin = () => {
// 设置空数组
const [records, setData] = useState([])
useEffect(() => {
const fetchdata = async () => {
const data = await fetch('http://localhost:5000/api/getproducts/')
const json = await data.json()
if (data.ok) {
setData(json)
}
}
fetchdata()
}, [])
return (
<div className='main-page'>
<img className='logo-admin' src='https://i.imgur.com/v10SbL4.png'></img>
<div className='productsdata'>
{records.length > 0 ?
records.map((record) => (
<RecordList key={record._id} record={record} />
)):
<p>No Record</p>
}
</div>
</div>
)
}
export default Productsadmin
英文:
You need to set initial state value as blank array as like
const [records, setData] = useState([])
then you can run your code.
I have also handled the error if Array is empty then it's showing No Record message.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
import { useEffect, useState } from 'react'
import '../adminInterface.css'
import RecordList from './recordList'
const Productsadmin = () => {
//set empty array
const [records, setData] = useState([])
useEffect(() => {
const fetchdata = async () => {
const data = await fetch('http://localhost:5000/api/getproducts/')
const json = await data.json()
if (data.ok) {
setData(json)
}
}
fetchdata()
}, [])
return (
<div className='main-page'>
<img className='logo-admin' src='https://i.imgur.com/v10SbL4.png'></img>
<div className='productsdata'>
{records.length>0 ?
records.map((record) => (
<RecordList key={record._id} record={record} />
)):
<p>No Record</p>
}
</div>
</div>
)
}
export default Productsadmin
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论