React(Class) - 다른 compoment에 state전달

 


import React, { Component } from 'react'
import New_compoment from './compoments/New_compoment';

export class App extends Component {

constructor(props){ // constructor를 만들어 props를 전달
super(props); // 기존의 props 유지

this.state = { // class이기 때문에 this를 사용
fruit : [ // 실제 상태를 바꿀 state.fruit
{ id: 0, post : 'apple'},
{ id: 1, post : 'banana'}

]
};

}

render() {
return (
<div>
<New_compoment fruit = {this.state.fruit}/>
</div> // New_compoment에 fruit state 전달
)
}
}

export default App

위의 코드에서 state를 추가하며 New_compoment에 fruit라는 props를 전달한다.


import React, { Component } from 'react'

export class New_compoment extends Component {
render(props) {
return (
<div>
{console.log(this.props.fruit) /*props 확인*/}
</div>
)
}
}

export default New_compoment

New_compoment에서 fruit가 제대로 전달이 됬는지 console.log로 확인합니다.



제대로 전달된 것을 console.log로 확인할수 있었습니다.


이제 fruit의 내용을 브라우저에 표시를 해야 합니다. 이를 위해 또다른 compoment를 만들어야 합니다.


import React, { Component } from 'react'

export class Print_fruit extends Component {
render(props) {
return (
<div>
<h1>{this.props.fruit.id}{"/"}{this.props.fruit.post}</h1>
</div>
)
}
}

export default Print_fruit


위와 같이 코드를 작성한다. h1태그에 fruit id, post를 각각 작성하고 출력하는 코드이다. props는 상위 compoment인 New_compoment에서 받는다.


import React, { Component } from 'react';
import Print_fruit from './Print_fruit'; // Print_fruit를 갖고온다

export class New_compoment extends Component {
render(props) {
return (
<div>
{this.props.fruit.map((ele) => {
return <Print_fruit fruit = {ele}/>
// map method를 사용하여 fruit의 갯수만큼 태그를 생성
})}
</div>
)
}
}

export default New_compoment


이제 New_compoment에서 Print_fruit를 갖고온다.  그리고 map 메소드를 이용하여 <Print_fruit />를 this.props.fruit의 크기만큼 만들어준다. 이때 ele는 fruit배열의 원소를 말하며 각각의 원소에 맞춰서 <Print_fruit />가 만들어져야 한다.



'npm start'를 하면 위와 같은 결과가 브라우저에 출력된다. 이때 에러가 발생이 된다. 




경고의 내용은 각 child에는 유일한 key값이 필요하다는 것이다. 처음에 state를 생성할때 id를 갖이 만든것을 알것이다. 결국 위 에러는 key값의 부재때문에 생긴 것이다.


import React, { Component } from 'react';
import Print_fruit from './Print_fruit'; // Print_fruit를 갖고온다

export class New_compoment extends Component {
render(props) {
return (
<div>
{this.props.fruit.map((ele) => {
return <Print_fruit key = {ele.id}fruit = {ele}/>
// map method를 사용하여 fruit의 갯수만큼 태그를 생성
// key값을 ele.id로 입력한다.
})}
</div>
)
}
}

export default New_compoment


이제 위의 코드처럼 다시 수정하고 돌리면 에러가 사라진것을 확인할수 있다.


지금은 원소가 2개이지만 만약 수십, 수천개의 원소를 출력할때는 단순시 id 1,2로 해결이 안된다. 물론 React는 프런트 엔드쪽이고 기본적으로 서버에서 id를 제공한다. 




이전글 : React(Class) - 다른 compoment로 전달

이후글 : React(Class) - 다른 compoment에 function전달












댓글

이 블로그의 인기 게시물

DAQ로 전압 측정하기-2

Nest JS URL에 있는 쿼리(Query) 읽기

appendChild를 이용하여
  • 늘리기_JavaScript_2번