• 카테고리

    질문 & 답변
  • 세부 분야

    프론트엔드

  • 해결 여부

    미해결

Props 전달과정에서 발생한 에러입니다.

20.11.07 15:59 작성 조회수 126

0

Error

Objects are not valid as a React child (found: object with keys {fruit, beverage}). If you meant to render a collection of children, use an array instead.

이란 에러가 발생했습니다.

 const fruits = [
        { fruit: '사과', beverage: '사과쥬스' },
        { fruit: '딸기', beverage: '딸기우유' },
        { fruit: '오렌지', beverage: '오렌지쥬스' }
    ]
    return (
        <>
            <h1>숫자야구</h1>
            <input maxLength={4} ref={input} type="number" onChange={onChangeHandler} value={myNumber} onKeyPress={onPressEnter}/>
            <button onClick={onClickHandler}>제출</button>
            <ul>
            {fruits.map((fruit, index)=>{
                return (
                    <Try 
                    fruit={fruit}
                    index={index}
                    />
                )
            })}

const React = require('react')

const Try = (fruit, index) => {
    return (
        <li>
            <div>{fruit.fruit}</div>
            <div>컨텐츠</div>
            <div>컨텐츠</div>
            <div>컨텐츠</div>
            <div>컨텐츠</div>
            <div>컨텐츠</div>
        </li>
    )
}

module.exports = Try

제가 생각한 시나리오는

1. fruits의 배열을 map 반복문으로 돌린다.

2. 객체의 데이터를 Try 데이터로 fruit로 보낸다.

3. Try 컴포넌트가 fruit을 받아 그 안의 fruit 만 출력한다.

4. 예상 결과는 사과, 딸기 오렌지 가 출력되는 것

자식 컴포넌트에 Props로 받아 props.fruit.fruit 하면 정상적으로 출력됩니다.

자식 컴포넌트의 Props로 전달받은 데이터를 선언해서 사용해도 되는 것으로 알고 있는데 잘못된 방식인가요?

답변 1

답변을 작성해보세요.

0

Try에서 (fruit, index)가 아니라 ({ fruit, index })입니다. (props) 자리인 것을 구조분해한 것입니다.