React Native

1. state 다루기 : prop 과 State

Machine_웅 2019. 12. 30. 15:10
728x90
반응형

Props란?

properties의 약어이며,

컴포넌트가 생성될 때,  매개변수로 props가 전달된다.

이렇게 받아온 데이터를 사용하는 것을 말한다.

변동되지 않는 데이터를 다룰 때 사용한다.

부모에 의해 설정되며, 컴포넌트가 살아있는 동안만 유지된다.

 

state와 다르게 props 는 컴포넌트 내에서 갱신되지 않는다.

 

State란?

state는 컴포넌트가 다루는 값들의 집합체,

리액트에서는 UI를 state를 다루는 기계장치로 보면된다.

 

setState함수를 사용해 state를 변경하게 되면, 리액트는 컴포넌트를 다시 랜더링 하게 된다.

 

만약에 자식 컴포넌트가 props에 부모의 state를 받아서 사용하게 된다면,
부모 컴포넌트의 state 값이 변경되면 자식 컴포넌트도 다시 렌더링 된다.

 

 

데이터를 컨트롤하는 방법에는 두 가지가 있다.

하나는 앞서 말한 props이고 다른 하나가 state이다.

prop와 달리 state는 변화하는 데이터를 다룰때 사용해야 한다.

 

 

State 사용방법

state는  컴포넌트가 생성될때 생성자나 속성 초기화를 통해서 초기화된다.

 

한번 초기화 된 state는  해당 컴포넌트 내에서 this.state.이름  을 통해서 사용 할 수 있다.

 

 

1. 초기화

 

1) 속성 초기화로 state 지정하기

 

export default class App extends Component{
  // state는 컴포넌트가 다루는 값들의 집합체이다.
  state = {
    year: 2020,
    name: 'Machine_Woong',
    colors:['blue','red']
  }

  render(){
 
    return(
      <View>

        <Text>My name is :{this.state.name}</Text>
        <Text>The year is :{this.state.year}</Text>
        <Text>My colors are :{this.state.colors[0]}</Text>

      </View>
    );
  }
}

 

2) 생성자로 state 지정하기

export default class App extends Component{
  // state는 컴포넌트가 다루는 값들의 집합체이다.

  constructor(){
    super()
    this.state={
      year: 2019,
      name: 'Machine_Woong_1',
      colors:['blue','red']
    }
  }


  render(){
 
    return(
      <View>

        <Text>My name is :{this.state.name}</Text>
        <Text>The year is :{this.state.year}</Text>
        <Text>My colors are :{this.state.colors[0]}</Text>

      </View>
    );
  }
}

1) 2) 중 어느 방법을 사용하던지 방식에는 차이가 없다.

 

 

2. 갱신하기 this.setState()

 

setState 메서드는 이전 내용과 새로운 state 내용을 병합한다.

따라서, key-value 형태로 이루어진 객체를 전달한다면  ex) age:99

기존의 값들은 유지가 되고 새로운 state가 추가된다.

 

다음 예제는

TEXT 는 터치시 state 의 year이 변경되는 코드이다.

 

export default class App extends Component{
  // state는 컴포넌트가 다루는 값들의 집합체이다.

  constructor(){
    super()
    this.state={
      year: 2019,
      name: 'Machine_Woong_1',
      colors:['blue','red']
    }
  }

  updateYear(){
    if(this.state.year == 2019){
      this.setState({
        year:2020
      })
    }else{
      this.setState({
        year:2019
      })
    }
  }


  render(){
 
    return(
      <View>

        <Text 
          onPress={() =>this.updateYear()}>
            The year is : { this.state.year}
        </Text>

      </View>
    );
  }
}

setState가 호출 될때마다 리엑트는 render 메서드를 다시 호출해서 컴포넌트와 자식 컴포넌트를 다시 랜더링한다.

 

간혹   updateYear메소드에서 state를 직접  this.state.year = 2022 이렇게 변경하려고 하는데 ui적으로는 갱신되지 않는다.

 

 

강제적으로 랜더링을 하게 하려면,

this.forceUpdate() 를 사용해야한다.

 

* this.setState 사용방법 권유

  // 이런 형태로 변화시키는 것을 권유한다. 
  testAlert(){
   
    this.setState(
      currnt =>({testVal : currnt.testVal +1})
    )

  }

 

 

 

 

 

다양한 데이터 타입으로 state 지정하기

export default class App extends Component{
  // state는 컴포넌트가 다루는 값들의 집합체이다.

  constructor(){
    super()
    this.state={
      year: 2020,
      name: 'Machine_Woong_1',
      colors:['blue','red'], // 배열
      leapYear:true, // boolean
      info:{
        paperback:true,
        length:'333 page',
        type:'programming'
      }  // 객체 
    }
  }


  render(){

    let leapYear = <Text>This is a not leapYear!! </Text>

    if(this.state.leapYear){
      leapYear = <Text>This is a leapYear~~~~!</Text>
    }
 
    return(
      <View>
        <Text>{this.state.year}</Text>
        <Text>객체안의 Length 값 은 : {this.state.info.length}</Text>
        <Text>객체안의 type 값 은 : {this.state.info.type}</Text>
        {leapYear}
      </View>
    );
  }
}

 

 

let은  코드블럭 내에서만 사용이 가능하고, 변수 재선언 불가능,  재할당은 가능한 데이터 타입? 이다.

비교,  const 재선언 재할당 불가능 하지만 Object의 deep value 값은 변경이 가능하다.
ex)

 const test1 = { 'a':1}

test1.a = 2 // 가능

 

728x90
반응형