source

오류: 정의되지 않은 속성 'map'을 읽을 수 없습니다.

nicesource 2023. 2. 23. 22:53
반응형

오류: 정의되지 않은 속성 'map'을 읽을 수 없습니다.

팔로우 하고 있습니다.reactjs튜토리얼, 그리고 나는 계속 문제에 부딪힌다.
한 구성요소 상태에서 다른 구성요소로 값을 전달합니다.

에러Cannot read property 'map' of undefined'튕겨져버립니다.map에서 기능하다CommentList컴포넌트가 실행됩니다.

의 원인이 되는 것은,prop되려고undefined에서 지나갈 때CommentBoxCommentList?

// First component
var CommentList = React.createClass({
  render: function() {
    var commentNodes = this.props.data.map(function (comment){
      return <div><h1>{comment.author}</h1></div>;
    });
    return <div className="commentList">{commentNodes}</div>;
  }
});
// Second component    
var CommentBox = React.createClass({
   getInitialState: function(){
     return {data: []};
   },
   getComments: function(){
      $.ajax({
        url: this.props.url,
        dataType: 'json',
        success: function(data){ this.setState({data: data}) }.bind(this),
        error: function(xhr, status, err){ console.error(url, status, err.toString()) }.bind(this)
      });
   },
   componentWillMount: function(){
      this.getComments()
   },
   render: function(){
      return <div className="commentBox">{<CommentList data={this.state.data.comments}/>}</div>;
   }
});

React.renderComponent( <CommentBox url="comments.json" />, document.getElementById('content'));

우선, 보다 안전한 초기 데이터를 설정합니다.

getInitialState : function() {
    return {data: {comments:[]}};
},

그리고 당신의 에이잭스 데이터를 확보하세요.

데모와 같이 위의 두 가지 지침을 따르면 작동합니다.

업데이트됨: .map 블록을 조건문으로 랩할 수 있습니다.

if (this.props.data) {
  var commentNodes = this.props.data.map(function (comment){
      return (
        <div>
          <h1>{comment.author}</h1>
        </div>
      );
  });
}

옷 갈아입는 걸 잊은 것 같은데

data={this.props.data}

로.

data={this.state.data}

CommentBox의 렌더링 기능에서 사용할 수 있습니다.저도 튜토리얼을 따라 할 때 같은 실수를 했어요.따라서 전체 렌더 함수는 다음과 같이 보여야 합니다.

render: function() {
  return (
    <div className="commentBox">
      <h1>Comments</h1>
      <CommentList data={this.state.data} />
      <CommentForm />
    </div>
  );
}

대신

render: function() {
  return (
    <div className="commentBox">
      <h1>Comments</h1>
      <CommentList data={this.props.data} />
      <CommentForm />
    </div>
  );

렌더링 전에 데이터를 입력해야 합니다.

다음과 같이 해야 합니다.

var data = [
  {author: "Pete Hunt", text: "This is one comment"},
  {author: "Jordan Walke", text: "This is *another* comment"}
];

React.render(
  <CommentBox data={data}/>,
  document.getElementById('content')
);

이것 대신:

React.render(
  <CommentBox data={data}/>,
  document.getElementById('content')
);

var data = [
  {author: "Pete Hunt", text: "This is one comment"},
  {author: "Jordan Walke", text: "This is *another* comment"}
];

에러"Cannot read property 'map' of undefined"에러가 발생했을 경우,"this.props.data"또는 propos.data array가 없습니다.

어레이를 체크하기 위한 조건을 설정하는 것이 좋습니다.

if(this.props.data){
this.props.data.map(........)
.....
}

바로 이 질문에 대해 태곤의 답변으로 코멘트를 하는 것을 검토했지만, 자세한 것에 관심이 있는 분에게는 설명이 더 필요하다고 생각했습니다.

Uncatched TypeError: Undefined 속성 'value'는 JavaScript 오류입니다.
(값은 무엇이든 될 수 있지만 이 질문의 값은 '맵'입니다.)

끝없는 디버깅 사이클을 피하기 위해서는 이 점을 이해하는 것이 중요합니다.
이 오류는 특히 JavaScript(및 라이브러리/프레임워크)에서 시작하는 경우에 자주 발생합니다.
위해서React이는 컴포넌트의 라이프 사이클 방법을 이해하는 것과 많은 관련이 있습니다.

// Follow this example to get the context
// Ignore any complexity, focus on how 'props' are passed down to children

import React, { useEffect } from 'react'

// Main component
const ShowList = () => {
  // Similar to componentDidMount and componentDidUpdate
  useEffect(() => {// dispatch call to fetch items, populate the redux-store})

  return <div><MyItems items={movies} /></div>
}

// other component
const MyItems = props =>
  <ul>
    {props.items.map((item, i) => <li key={i}>item</li>)}
  </ul>


/**
  The above code should work fine, except for one problem.
  When compiling <ShowList/>,
  React-DOM renders <MyItems> before useEffect (or componentDid...) is called.
  And since `items={movies}`, 'props.items' is 'undefined' at that point.
  Thus the error message 'Cannot read property map of undefined'
 */

이 문제를 해결하기 위한 방법으로 @taggon은 해결책을 제시했습니다(첫 번째 anwser 또는 link 참조).

솔루션:초기값/기본값을 설정합니다.
이 예에서는, 다음과 같이 회피할 수 있습니다.items선언함으로써 '불명예'가 되는 것default빈 배열 값입니다.

왜? 이렇게 하면 React-DOM에서 처음에 빈 목록을 렌더링할 수 있습니다.
그리고 그 때useEffect또는componentDid...메서드가 실행되고 컴포넌트가 채워진 항목 목록으로 다시 표시됩니다.

// Let's update our 'other' component
// destructure the `items` and initialize it as an array

const MyItems = ({items = []}) =>
  <ul>
    {items.map((item, i) => <li key={i}>item</li>)}
  </ul>

문제는 다음과 같습니다.

{props.users.map((item,index)=>(
    <div className="items" key={index}>
        <div className="text-center">
            <p className="fs-12">{item}</p>
        </div>
    </div>
))}

그리고 이 코드를 추가하는 문제를 해결했습니다.이것은 마치 문과 같게 동작합니다.

{ props.users ? props.users.map((item,index)=>(
        <div className="items" key={index}>
            <div className="text-center">
                <p className="fs-12">{item}</p>
            </div>
        </div>
)) : <p>Users is empty</p>}

이 에러는, 주로 어레이를 찾을 수 없기 때문에 발생합니다.올바른 배열에 매핑되었는지 확인합니다.어레이 이름 또는 선언을 확인합니다.

저 같은 경우에는 Promise에 유형을 추가하려고 하면 발생합니다.모든 핸들러:

Promise.all([1,2]).then(([num1, num2]: [number, number])=> console.log('res', num1));

" " " " ": [number, number]에러가 해소되었습니다.

저는 이게 잘 먹혔어요. 소품을 쓰면.worktyp.map 이 맵의 에러는 정의되어 있지 않습니다.

//App.js
    const worktyp = [
          "Full-time",
          "casual",
          "part-time",
          "contract"
        ];
    
    function Main(props){
      return(
    <section>
      <p>This the main body</p>
      <ul style = {{textAlign:"left"}}>
        **{worktyp.map((work) => <li>{work}</li>)}**
      </ul>
    </section>
    
      );
        }
 function App() {
      return (
        <div className="App">
          <Header name="initial"/>
          **<Main work={worktyp}/>**
          <Foot year ={new Date().getFullYear()}/>
        </div>
      );
    }
//index.js
    ReactDOM.render(
     <App />,
      document.getElementById('root')
    );

api 호출 데이터 앱 [{programname: "string", 상태: "status"}]에 반응합니다.

저의 경우, "?" 조건을 추가하여 이 오류를 해결했습니다.

이전:

<div className="hotelContainer__img">
              {photos.map((item, index) => (
                <img
                  src={item}
                  alt=""
                  key={index}
                  onClick={() => handleOpen(index)}
                />
              ))}
            </div>

끝나고

<div className="hotelContainer__img">
              {photos?.map((item, index) => (
                <img
                  src={item}
                  alt=""
                  key={index}
                  onClick={() => handleOpen(index)}
                />
              ))}
            </div>

언급URL : https://stackoverflow.com/questions/24706267/error-cannot-read-property-map-of-undefined

반응형