programing

× TypeError: 정의되지 않은 속성을 읽을 수 없습니다('map' 읽기).

golfzon 2023. 2. 28. 23:57
반응형

× TypeError: 정의되지 않은 속성을 읽을 수 없습니다('map' 읽기).

이 코드를 실행하려고 하면 다음 오류가 나타납니다.

× TypeError: 정의되지 않은 속성을 읽을 수 없습니다('map' 읽기).

왜 이렇게 될까요?어떻게 하면 될까요?

import React from 'react';
import Grid from '@material-ui/core/Grid';

import Product from './Product/Product';
import useStyles from './styles';

const products = [
  {id: 1, name: 'Shoes', description: 'Running Shoes.' },
  {id: 2, name: 'MacBook', description: 'Apple MacBook.' },
];

const Products = ({ products }) => {
  const classes = useStyles();

  return (
    <main className={classes.content}>
      <div className={classes.toolbar} />
      <Grid container justify="center" spacing={4}>
        {products.map((products) => (
          <Grid item key={product.id} item xs={12} sm={6} md={4} lg={3}>
            <Product />
          </Grid>
        ))};
      </Grid>
    </main>
  );
};

export default Products;

같은 오류가 발생하여 어레이가 존재하는지 먼저 물어보고 해결했습니다.

예:

<Filter>
  { product.color?.map((c) => (
    <FilterColor color = {c} key = {c} />
  ))};
</Filter>

컴포넌트에 속성 "제품"이 있습니다.이 변수는 외부에 있는 맵보다 우선순위가 높고.map사용하고 있습니다.같은 이름의 변수를 피하기 위해 이들 중 하나의 이름을 변경할 것을 권장합니다.

에러로 보아 그 속성은 컴포넌트에 전달되지 않은 것 같습니다.

또한 map lamda의 파라미터도 "products"입니다."product"로 변경하지 않으면 실패합니다.

속성,products컴포넌트에 전달한다(Products)는 정의되어 있지 않습니다.Map 메서드는 다음 사항을 고려합니다.products속성으로 전달된 것은 컴포넌트 자체 외부에 생성된 것이 아닙니다.

를 계획하는 경우products컴포넌트 외부에 작성한 어레이는 전달된 속성과 이름이 같기 때문에 이름을 변경하기만 하면 됩니다.를 사용하는 경우products(속성으로부터) 컴포넌트의 속성을 전달하고 있는지 확인합니다.

이는 어레이 "products"와 맵 항목 "products"의 이름이 같기 때문입니다.지도 항목을 "product"와 같은 다른 항목으로 변경합니다.

const products = [
        {id: 1, name: 'Shoes', description: 'Running Shoes.' },
        {id: 2, name: 'MacBook', description: 'Apple MacBook.' },
    ];

const Products = ({ products }) => {
  const classes = useStyles();

  return (
    <main className={classes.content}>
      <div className={classes.toolbar} />
      <Grid container justify="center" spacing={4}>
        {products.map((product) => (
          <Grid item key={product.id} item xs={12} sm={6} md={4} lg={3}>
            <Product/>
          </Grid>
        ))};
      </Grid>
    </main>
  );
};

빈 어레이[]가 표시됩니다.이 때문에, 이 에러가 발생하고 있습니다.이 문제는 다음 두 가지 방법으로 해결할 수 있습니다.

{products && products.map((product) => (
    <Grid item key={product.id} item xs={12} sm={6} md={4} lg={3}>
        <Product/>
    </Grid>
))};

또는

{products?.map((product) => (
    <Grid item key={product.id} item xs={12} sm={6} md={4} lg={3}>
        <Product/>
    </Grid>
))};

다음과 같이 쓰면 문제가 해결됩니다.

<Grid container justify="center" spacing={4}>
  {products ?.map((product) => (
    <Grid item key={product.id} item xs={12} sm={6} md={4} lg={3}>
      <Product/>
    </Grid>
  ))};
</Grid>

제품 속성을 제품 구성 요소에 전달해야 합니다.변경:

{products.map((products) => (
              <Grid item key={product.id} item xs={12} sm={6} md={4} lg={3}>
                <Product/>

다음과 같이 입력합니다.

{products.map((products) => (
              <Grid item key={products.id} item xs={12} sm={6} md={4} lg={3}>
                <Product/>

왜? 이 경우 오브젝트(제품)를 <제품/> 컴포넌트인 JSX 요소에 매핑하기 때문에 {product.id}을(를) 사용하여 정의되지 않은 오브젝트를 매핑하려고 합니다.그런 다음 매핑하려는 제품 속성이 제품 구성 요소를 사용하여 상위 구성 요소로 올바르게 전달되었는지 확인하십시오.

우선 수출하고 있는지 확인해 주세요.만약 그렇다면, 변경하세요.

{products.map((products) => (
  <Grid item key={product.id} item xs={12} sm={6} md={4} lg={3}>
  <Product/>

로.

{products.map((products) => (
   <Grid item key={products.id} item xs={12} sm={6} md={4} lg={3}>
   <Product/>

여기에서는 제품을 제품으로 매핑하기 때문에 키를 다음과 같이 설정해야 합니다.products.id.

맵 메서드의 각 반복에 제품 이름을 붙였지만 제품을 사용하여 반복의 각 인스턴스를 포착하고 있습니다.

순서 1: 사용자 페이지에 로드 추가 - useState 사용

{const [loading, setLoading] = useState(true);}

스텝 2: 비동기 가져오기 기능 종료 시 로드 값을 false로 설정합니다.try-catch 방식을 사용하는 경우 try 방식 안에 다음 코드줄을 넣습니다.

  {   setLoading(false)}

스텝 3: 코드의 render() 부분 내부에서 단항 연산을 사용합니다.

{ loading ? (
  <h2>loading</h2>
) :  {/* Enter code here */}}

다음과 같이 지도 부분을 교체할 수 있습니다.

{(products|| []).map(product) => ( // Your code ))}

속성이 정의되어 있지 않은지 확인합니다.

typeof products.map() !== undefined

용도:

const Products = ({ products }) => {
  const classes = useStyles();

  return (
    <main className={classes.content}>
      <div className={classes.toolbar} />
      <Grid container justify="center" spacing={4}>
        {products && products.map((products) => (
          <Grid item key={product.id} item xs={12} sm={6} md={4} lg={3}>
            <Product />
          </Grid>
        ))};
      </Grid>
    </main>
  );
};

'우리끼리'를 붙이면 돼요.products && 여부가 됩니다." 맵이 정의되어 있는지 여부를 확인합니다.

        {products && products.map((product) => (
          <Grid item key={product.id} item xs={12} sm={6} md={4} lg={3}>
            <Product />
          </Grid>
        ))};

useState 변수를 사용하지 않으면 오류가 발생할 수 있습니다.

그리고 다른 2개의 컴포넌트를 만들었습니다.1) Tour 2) Tours

 const [tours, setTours ] = useState([]);

투어 변수를 App.js 파일에서 Tours 컴포넌트를 사용하여 사용했습니다.

App.js

App.js 파일에서 투어를 사용한 적이 있습니다.

App.js

이제 Tours.js 파일의 .map() 함수를 사용하기 위한 Tours 변수를 가져갑니다.

const Tours = ({ tours }) => {
/...
{tours.map()
.../

Tours.js

두 파일의 철자가 동일한지 확인해야 합니다.그렇지 않으면 오류가 발생하고 특정 파일의 UI도 작동하지 않습니다.

다음을 시도해 보십시오.

{products.map((product) => (
  <Grid item key={product.id} item xs={12} sm={6} md={4} lg={3}>
    <Product/>
  </Grid>
))};

제품 컴포넌트 내부에 어떠한 정보(prop)도 전달하지 않기 때문에 이러한 오류가 발생하였습니다.그럼 이렇게 해 보세요.

return (
    <main className={classes.content}>
      <div className={classes.toolbar} />
      <Grid container justify="center" spacing={4}>
        {products.map((products) => (
          <Grid item key={product.id} item xs={12} sm={6} md={4} lg={3}>
            <Product product={product} />
          </Grid>
        ))};
      </Grid>
    </main>
  );
};

기본적으로 수신된 값이 정의되지 않았는지 확인해야 합니다.

Angular에서는 다음과 같은 기능을 사용할 수 있습니다.{{person?.name}}.

용도:

  <Grid container justify="center" spacing={4}>
    {products && products.map((products) => (
      <Grid item key={product.id} item xs={12} sm={6} md={4} lg={3}>
        <Product />
      </Grid>
    ))};
  </Grid>

여기서 products.map() 대신 products & products.map()변경됩니다.

//Just use 
{products && products.map((products) => (
       <Grid item key={product.id} item xs={12} sm={6} md={4} lg={3}>
     <Product />
   </Grid>
))};

// add "products &&" before the map method

const Products = ({ products }) => {
  const classes = useStyles();

  return (
    <main className={classes.content}>
      <div className={classes.toolbar} />
      <Grid container justify="center" spacing={4}>
        {products?.map((products) => (
          <Grid item key={product.id} item xs={12} sm={6} md={4} lg={3}>
            <Product />
          </Grid>
        ))};
      </Grid>
    </main>
  );
};

용도:

 { product.color?.map((c) => (
    <FilterColor color = {c} key = {c} />
  ))};

이렇게 하면 문제가 해결되는데, 왜 이런 문제가 이면에서만 나타나는 걸까요?반응으로 상태가 즉시 업데이트되지 않습니다.이 개념을 스케줄링이라고 합니다.이 때문에 products.map에 접속하면 제품이 빈 배열이 됩니다.

리듀서의 INITIAL_STATE를 체크합니다.

리듀서에서 호출하는 ID 개체에서 배열을 지정해야 합니다.

예:

const INTIAL_STATE = {
    products: [],
    product: { name: "", brand_name: "", prices: "", color: "", images: []},
    error: "",
}

product.images.map(img => {
    return(
        <div key = {img.id} className = "img-itemm">
            <img src = {img.image} alt = {img.image} />
        </div>
    )
})

언급URL : https://stackoverflow.com/questions/69080597/%c3%97-typeerror-cannot-read-properties-of-undefined-reading-map

반응형