简体   繁体   English

数据map function在Reactjs不工作

[英]Data map function is not working in Reactjs

I am working with Reactjs and using nextjs framework,Right now i am trying to fetch data (url is - https://dummyjson.com/products ) using map function but i am getting following error我正在使用 Reactjs 并使用 nextjs 框架,现在我正在尝试使用 map function 获取数据(url 是 - https://dummyjson.com/products ),但我收到以下错误

TypeError: Cannot read property 'length' of undefined

Here is my current code这是我当前的代码

import { useEffect, useState } from "react"
export default function Test() {
  const [data, setData] = useState<any>();
  useEffect(() => {
    const callData = async () => {
      const data = await fetch('https://dummyjson.com/products').then(data => data.json())
      console.log(data);
      setData(data)
    }
    callData()
  }, [])

  return(
    <div>
    {
     data.length ? data.map(({}) => <p key={data.id}>{data.title}</p>) : <h3>There are no records yet</h3>
    }
    </div>)

}
  • Initially data is undefined , so use optional chaining to check nested properties.最初dataundefined的,所以使用可选链接来检查嵌套属性。
  • The returned data is an object;返回的数据是一个object; you want to access the products field.您要访问products字段。
  • Name the first parameter to the Array#map callback so you can actually access it.将第一个参数命名为Array#map回调,以便您可以实际访问它。
{data?.products?.length ? data.products.map(product => <p key={product.id}>{product.title}</p>) 
       : <h3>There are no records yet</h3>}

Try to initialize data state with an empty array:尝试用空数组初始化data state:

 const [data, setData] = useState<any>([]);

You should also change你也应该改变

 data.map(({}) => <p key={data.id}>{data.title}</p>)

to

 data?.map(({id,title}) => <p key={id}>{title}</p>)

//Follow this code. your data in the products array so if you want to map then you have to pass array.

  import { useEffect, useState } from "react";
    export default function Test() {
      const [data, setData] = useState<any[]>([]);
      useEffect(() => {
        const callData = async () => {
          const data = await fetch('https://dummyjson.com/products').then(data => data.json())
          console.log(data);
          setData(data?.products)
        }
        callData()
      }, [])
    
      return(
        <div>
        {
         data.length ? data.map((product) => <p key={product.id}>{product.title}</p>) : <h3>There are no records yet</h3>
        }
        </div>)
    
    }

The problem with your code is that you are missing the destructuring of elements in the map function. The correct way would be您的代码的问题是您缺少 map function 中元素的解构。正确的方法是

{
  data.length ? data.map(({title, id}) => <p key={id}>{title}</p>) : 
 <h3>There are no records yet</h3>
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM