简体   繁体   English

反应处理 state

[英]React handling state

I'm trying to make an e-commerce app, and I've just started the project, but I keep getting an error.我正在尝试制作一个电子商务应用程序,并且我刚刚启动了该项目,但我不断收到错误消息。 Every time i try to get the information from my data component and then map through it, I get 'Cannot read property 'map' of undefined'.每次我尝试从我的数据组件中获取信息,然后通过它获取 map 时,我都会得到“无法读取未定义的属性 'map'”。 can someone help me with that?有人可以帮我吗? Here are the components:以下是组件:

import React, { useState, useEffect } from 'react';
import './App.css';

import { Routes } from './routes'
import { Main } from './components/Main'
import { storeProducts } from './data/data'

function App() {

  const [items, setItems] = useState([])

  useEffect(() => {
      setItems(storeProducts)
  }, [])

  return (
    <div className="App">
       <Routes />
       <Main items={items} />
    </div>
  );
}

export default App;
import React from 'react'

import { ItemComponent } from './ItemComponent'

export const Main = ({items}) => {

    const products = items.map(() => <ItemComponent />)

    return (
        <div>
           {products}
        </div>
    )
}
import React from 'react'

export const ItemComponent = ({details}) => {
    return (
        <div>
            Hello Item
        </div>
    )
}

data used使用的数据

export const storeProducts = [
    {
      id: 1,
      title: "Google Pixel - Black",
      img: "img/product-1.png",
      price: 10,
      company: "GOOGLE",
      info:
        "Lorem ipsum dolor amet offal butcher quinoa sustainable gastropub, echo park actually green juice sriracha paleo. Brooklyn sriracha semiotics, DIY coloring book mixtape craft beer sartorial hella blue bottle. Tote bag wolf authentic try-hard put a bird on it mumblecore. Unicorn lumbersexual master cleanse blog hella VHS, vaporware sartorial church-key cardigan single-origin coffee lo-fi organic asymmetrical. Taxidermy semiotics celiac stumptown scenester normcore, ethical helvetica photo booth gentrify.",
      inCart: false,
      count: 0,
      total: 0
    },
    {
      id: 2,
      title: "Samsung S7",
      img: "img/product-2.png",
      price: 16,
      company: "SAMSUNG",
      info:
        "Lorem ipsum dolor amet offal butcher quinoa sustainable gastropub, echo park actually green juice sriracha paleo. Brooklyn sriracha semiotics, DIY coloring book mixtape craft beer sartorial hella blue bottle. Tote bag wolf authentic try-hard put a bird on it mumblecore. Unicorn lumbersexual master cleanse blog hella VHS, vaporware sartorial church-key cardigan single-origin coffee lo-fi organic asymmetrical. Taxidermy semiotics celiac stumptown scenester normcore, ethical helvetica photo booth gentrify.",
      inCart: false,
      count: 0,
      total: 0
    },
    {
      id: 3,
      title: "HTC 10 - Black",
      img: "img/product-3.png",
      price: 8,
      company: "htc",
      info:
        "Lorem ipsum dolor amet offal butcher quinoa sustainable gastropub, echo park actually green juice sriracha paleo. Brooklyn sriracha semiotics, DIY coloring book mixtape craft beer sartorial hella blue bottle. Tote bag wolf authentic try-hard put a bird on it mumblecore. Unicorn lumbersexual master cleanse blog hella VHS, vaporware sartorial church-key cardigan single-origin coffee lo-fi organic asymmetrical. Taxidermy semiotics celiac stumptown scenester normcore, ethical helvetica photo booth gentrify.",
      inCart: false,
      count: 0,
      total: 0
    },
    {
      id: 4,
      title: "HTC 10 - White",
      img: "img/product-4.png",
      price: 18,
      company: "htc",
      info:
        "Lorem ipsum dolor amet offal butcher quinoa sustainable gastropub, echo park actually green juice sriracha paleo. Brooklyn sriracha semiotics, DIY coloring book mixtape craft beer sartorial hella blue bottle. Tote bag wolf authentic try-hard put a bird on it mumblecore. Unicorn lumbersexual master cleanse blog hella VHS, vaporware sartorial church-key cardigan single-origin coffee lo-fi organic asymmetrical. Taxidermy semiotics celiac stumptown scenester normcore, ethical helvetica photo booth gentrify.",
      inCart: false,
      count: 0,
      total: 0
    },
    {
      id: 5,
      title: "HTC Desire 626s",
      img: "img/product-5.png",
      price: 24,
      company: "htc",
      info:
        "Lorem ipsum dolor amet offal butcher quinoa sustainable gastropub, echo park actually green juice sriracha paleo. Brooklyn sriracha semiotics, DIY coloring book mixtape craft beer sartorial hella blue bottle. Tote bag wolf authentic try-hard put a bird on it mumblecore. Unicorn lumbersexual master cleanse blog hella VHS, vaporware sartorial church-key cardigan single-origin coffee lo-fi organic asymmetrical. Taxidermy semiotics celiac stumptown scenester normcore, ethical helvetica photo booth gentrify.",
      inCart: false,
      count: 0,
      total: 0
    },
    {
      id: 6,
      title: "Vintage Iphone",
      img: "img/product-6.png",
      price: 17,
      company: "apple",
      info:
        "Lorem ipsum dolor amet offal butcher quinoa sustainable gastropub, echo park actually green juice sriracha paleo. Brooklyn sriracha semiotics, DIY coloring book mixtape craft beer sartorial hella blue bottle. Tote bag wolf authentic try-hard put a bird on it mumblecore. Unicorn lumbersexual master cleanse blog hella VHS, vaporware sartorial church-key cardigan single-origin coffee lo-fi organic asymmetrical. Taxidermy semiotics celiac stumptown scenester normcore, ethical helvetica photo booth gentrify.",
      inCart: false,
      count: 0,
      total: 0
    },
    {
      id: 7,
      title: "Iphone 7",
      img: "img/product-7.png",
      price: 30,
      company: "apple",
      info:
        "Lorem ipsum dolor amet offal butcher quinoa sustainable gastropub, echo park actually green juice sriracha paleo. Brooklyn sriracha semiotics, DIY coloring book mixtape craft beer sartorial hella blue bottle. Tote bag wolf authentic try-hard put a bird on it mumblecore. Unicorn lumbersexual master cleanse blog hella VHS, vaporware sartorial church-key cardigan single-origin coffee lo-fi organic asymmetrical. Taxidermy semiotics celiac stumptown scenester normcore, ethical helvetica photo booth gentrify.",
      inCart: false,
      count: 0,
      total: 0
    },
    {
      id: 8,
      title: "Smashed Iphone",
      img: "img/product-8.png",
      price: 2,
      company: "apple",
      info:
        "Lorem ipsum dolor amet offal butcher quinoa sustainable gastropub, echo park actually green juice sriracha paleo. Brooklyn sriracha semiotics, DIY coloring book mixtape craft beer sartorial hella blue bottle. Tote bag wolf authentic try-hard put a bird on it mumblecore. Unicorn lumbersexual master cleanse blog hella VHS, vaporware sartorial church-key cardigan single-origin coffee lo-fi organic asymmetrical. Taxidermy semiotics celiac stumptown scenester normcore, ethical helvetica photo booth gentrify.",
      inCart: false,
      count: 0,
      total: 0
    }
  ];

Seems strange but try this:看起来很奇怪,但试试这个:

export const Main = ({items}) => {

    if (!items) return <div/>

    const products = items.map(() => <ItemComponent />)

    return (
        <div>
           {products}
        </div>
    )
}

And see if it renders.看看它是否呈现。 setState is async and sometimes that causes this issue. setState 是异步的,有时会导致此问题。

Your error mean that you use .map function on a variable which has undefined value.您的错误意味着您在具有未定义值的变量上使用.map function 。 Here I have some feedbacks to improve your code:在这里,我有一些反馈可以改进您的代码:

No need to use useEffect in App component:无需在 App 组件中使用 useEffect:

function App() {   
  const [items, setItems] = useState(storeProducts);

  return (
    <div className="App">
       <Routes />
       <Main items={items} />
    </div>
  );
}

And Main component:主要成分:

export const Main = ({items}) => {
    const products = (items || []).map(() => <ItemComponent />)

    return (
        <div>
           {products}
        </div>
    )
}

items ||项目 || [] mean: if items is undefined then use empty array. []意思是:如果项目未定义,则使用空数组。 And then no error "Cannot read property 'map' of undefined" anymore.然后不再出现错误“无法读取未定义的属性'map'”。

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

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