React js – Uncaught TypeError: records.map is not a function

huangapple go评论69阅读模式
英文:

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 &#39;react&#39;
import &#39;../adminInterface.css&#39;
import RecordList from &#39;./recordList&#39;




const Productsadmin = () =&gt; {

    const [records, setData] = useState(null)

    useEffect(() =&gt; {
        const fetchdata = async () =&gt; {
            const data = await fetch(&#39;http://localhost:5000/api/getproducts/&#39;)
            const json = await data.json()

            if (data.ok) {
                setData(json)
            }
        }
        fetchdata()
        
        },[])




    return (
        &lt;div className=&#39;main-page&#39;&gt;
          &lt;img className=&#39;logo-admin&#39; src=&#39;https://i.imgur.com/v10SbL4.png&#39;&gt;&lt;/img&gt;
          &lt;div className=&#39;productsdata&#39;&gt;
            {records &amp;&amp; records.map((record) =&gt; (
                &lt;RecordList key={record._id} record={record} /&gt;
            ))}
          &lt;/div&gt;
        &lt;/div&gt;
    )
}

export default Productsadmin

and here's the recordlist.js code

const RecordList = ({ record }) =&gt; {
    return (
        &lt;div className=&quot;record-details&quot;&gt;
            &lt;h4&gt;{record.productName}&lt;/h4&gt;
            &lt;p&gt;&lt;strong&gt;Location : &lt;/strong&gt;{record.location}&lt;/p&gt;
            &lt;p&gt;&lt;strong&gt;Photo : &lt;/strong&gt;{record.photo}&lt;/p&gt;
        &lt;/div&gt;
    )
}

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 &#39;react&#39;
import &#39;../adminInterface.css&#39;
import RecordList from &#39;./recordList&#39;

const Productsadmin = () =&gt; {
  const [records, setData] = useState([]) // Initialize to an empty array

  useEffect(() =&gt; {
    const fetchdata = async () =&gt; {
      const data = await fetch(&#39;http://localhost:5000/api/getproducts/&#39;)
      const json = await data.json()

      if (data.ok) {
        setData(json)
      }
    }
    fetchdata()
  }, [])

  return (
    &lt;div className=&#39;main-page&#39;&gt;
      &lt;img className=&#39;logo-admin&#39; src=&#39;https://i.imgur.com/v10SbL4.png&#39;&gt;&lt;/img&gt;
      &lt;div className=&#39;productsdata&#39;&gt;
        {records.map((record) =&gt; (
          &lt;RecordList key={record._id} record={record} /&gt;
        ))}
      &lt;/div&gt;
    &lt;/div&gt;
  )
}

export default Productsadmin

答案2

得分: 1

以下是您要翻译的内容:

"Your code中有两个错误。请检查此Expo Snack(用于RN,但逻辑相同):https://snack.expo.dev/@zvona/async-fetch

我会详细说明:

  1. 为了类型安全,使用一个空数组进行初始化:const [records, setData] = useState([]);
  2. 用于处理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&#39;ll elaborate:
1. for type safety, use an empty array for init: `const [records, setData] = useState([]);`
2. for handling JSON data, please confirm it&#39;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 &#39;react&#39;
import &#39;../adminInterface.css&#39;
import RecordList from &#39;./recordList&#39;

const Productsadmin = () =&gt; {
  //set empty array
  const [records, setData] = useState([]) 

  useEffect(() =&gt; {
    const fetchdata = async () =&gt; {
      const data = await fetch(&#39;http://localhost:5000/api/getproducts/&#39;)
      const json = await data.json()

      if (data.ok) {
        setData(json)
      }
    }
    fetchdata()
  }, [])

  return (
    &lt;div className=&#39;main-page&#39;&gt;
      &lt;img className=&#39;logo-admin&#39; src=&#39;https://i.imgur.com/v10SbL4.png&#39;&gt;&lt;/img&gt;
      &lt;div className=&#39;productsdata&#39;&gt;
        {records.length&gt;0 ? 
            records.map((record) =&gt; (
              &lt;RecordList key={record._id} record={record} /&gt;
            )):
              &lt;p&gt;No Record&lt;/p&gt;
        }
      &lt;/div&gt;
    &lt;/div&gt;
  )
}

export default Productsadmin

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年3月9日 18:34:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/75683402.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定