본문 바로가기
FE/React & RN

[ React-Native ] 라이브러리 정리

by Chars4785 2019. 11. 5.

@ 궁금한 이유? 

> app 안에 있는 수많은 라이브러리 의 있는 이유를 알고 싶어서

 

List

- react-native-appsflyer

- react-native-global-props

- react-native-keep-awake

- react-native-secure-key-store
-  react-native-config

-  mobx


@ 공부

1. react-native-appsflyer

AppsFlyer SDK는 앱 설치 및 이벤트를 트래킹하는 기능을 제공합니다. 

 

2. react-native-global-props

import {
    setCustomView,
    setCustomTextInput,
    setCustomText,
    setCustomImage,
    setCustomTouchableOpacity
  } from 'react-native-global-props';

View, TextInput, Text, Image, TouchableOpacity  에 대한 기본 값을 설정 할 수 있습니다.

 

https://www.npmjs.com/package/react-native-global-props

 

// Setting a default background color for all View components.
const customViewProps = {
  style: {
    backgroundColor: '#d3d3d3' // light gray
  }
};
 
// Getting rid of that ugly line on Android and adding some custom style to all TextInput components.
const customTextInputProps = {
  underlineColorAndroid: 'rgba(0,0,0,0)',
  style: {
    borderWidth: 1,
    borderColor: 'gray',
    paddingVertical: 5,
    paddingHorizontal: 10,
    backgroundColor: 'white'
  }
};

커스텀으로 만들어서 사용 가능합니다.

3. react-native-keep-awake

> This React Native package allows you to prevent the screen from going to sleep while your app is active. It's useful for things like navigation or video playback, where the user expects the app to remain visible over long periods without touch interaction.

> 계속 앱이 켜져 있도록 돕는다. 

> 안에 코드를 보면 그런게 구성되어있다. mounted 를 올리면서 앱이 계속 켜져 있도록 돕고 있다.

import React, { Component } from 'react';
import { NativeModules } from 'react-native';

let mounted = 0;

export default class KeepAwake extends Component<{}> {
  static activate() {
    NativeModules.KCKeepAwake.activate();
  }

  static deactivate() {
    NativeModules.KCKeepAwake.deactivate();
  }

  componentDidMount() {
    mounted++;
    KeepAwake.activate();
  }

  componentWillUnmount() {
    mounted--;
    if (!mounted) {
      KeepAwake.deactivate();
    }
  }

  render() {
    return null;
  }
}

출처: https://github.com/corbt/react-native-keep-awake/blob/master/index.js

 

4. react-native-secure-key-store

5. react-native-config

 

6.  mobx

 

> 리액트 상태 관리 라이브러리

> https://hyunseob.github.io/2017/10/18/mobx-with-react/

> https://github.com/FEDevelopers/tech.description/wiki/React-Native-with-Mobx---Getting-Started

> https://mobx-react.js.org/state-local

> https://github.com/mobxjs/mobx-react

 

중요한 4가지 개념

 

1. Observable State (관찰 받고 있는 상태)

MobX 를 사용하고 있는 앱의 상태는 Observable 합니다. 이를 직역하자면 이 상태는 관찰 할 수 있는 상태인데요, 어쩌면 관찰 받고 있는 상태라고 이해하는게 조금 더 쉬울 수도 있겠습니다. 우리의 앱에서 사용하고있는 상태는, 변할 수 있으며, 만약에 특정 부분이 바뀌면, MobX 에서는 정확히 어떤 부분이 바뀌었는지 알 수 있습니다. 그 값이, 원시적인 값이던, 객체이던, 배열 내부의 객체이던 객체의 키이던 간에 말이죠.

 

2. Computed Value (연산된 값)

연산된 값은, 기존의 상태값과 다른 연산된 값에 기반하여 만들어질 수 있는 값입니다. 이는 주로 성능 최적화를 위하여 많이 사용됩니다. 어떤 값을 연산해야 할 때, 연산에 기반되는 값이 바뀔때만 새로 연산하게 하고, 바뀌지 않았다면 그냥 기존의 값을 사용 할 수 있게 해줍니다.

이를 이해하기 위해 간단한 예시를 들어보겠습니다. 우리가 편의점에서 800원짜리 물을 네병 샀는데 이게 얼마나오지? 하고 체크하는 함수 total() 이라는 함수가 있다고 가정하겠습니다. 우리가 처음 머릿속으로 계산할때 암산으로 4 * 8 에 32! 라면서 3,200 원이군, 하고 간단히 계산을 하겠죠. 잠시 후에 친구가 그거 다 얼마냐고 또 물어봅니다. 이 때 우리는 머릿속에서 별 생각안하고 응 3,200원이야 라고 말합니다. 친구가, 나도 한병 사줘! 하면 이때 다시 우리는 무의식중에 800원을 더해서 우리가 내야 할 돈이 4,000원인걸 연산합니다.

 

3. Reactions (반응)

Reactions 는 Computed Value 와 비슷한데요, Computed Value 의 경우는 우리가 특정 값을 연산해야 될 때 에만 처리가 되는 반면에, Reactions 은, 값이 바뀜에 따라 해야 할 일을 정하는 것을 의미합니다. 예를 들어서 Observable State 의 내부의 값이 바뀔 때, 우리가 console.log('ㅇㅇㅇ가 바뀌었어!') 라고 호출해 줄 수 있습니다.

 

4. Actions (액션; 행동)

액션은, 상태에 변화를 일으키는것을 말합니다. 만약에 Observable State 에 변화를 일으키는 코드를 호출한다? 이것은 하나의 액션입니다. - 리덕스에서의 액션과 달리 따로 객체형태로 만들지는 않습니다.

 

5. inject ( 주입하다. )

inject 함수는 mobx-react 에 있는 함수로서, 컴포넌트에서 스토어에 접근할 수 있게 해줍니다. 정확히는, 스토어에 있는 값을 컴포넌트의 props 로 "주입"을 해줍니다.

 

class Counter extends Component {
  number = 0;

  increase = () => {
    this.number++;
  }

  decrease = () => {
    this.number--;
  }

  render() {
    return (
      <div>
        <h1>{this.number}</h1>
        <button onClick={this.increase}>+1</button>
        <button onClick={this.decrease}>-1</button>
      </div>
    );
  }
}

decorate(Counter, {
  number: observable,
  increase: action,
  decrease: action
})

export default observer(Counter);

 

number가 변하게 되면 setState 없이 그냥 값 바꿔주면 알아서 렌더링해줍니다. 어떻게 알아서 렌더링해주냐구요? 코드 최하단에서 사용된 observer 가 observable 값이 변할 때 컴포넌트의 forceUpdate 를 호출하게 함으로써 자동으로 변화가 화면에 반영됩니다.

 


연습

export default class TestStrore {
    constructor(rootStore) {
        this.rootStore = rootStore;
        this.id = "TestStore";
        this.num = 0
    }

    changeID( newID ){
        this.id = newID
    }

    getID(){
        return this.id;
    }

    getStore(){
        return this.rootStore;
    }   

    getNum(){
        return this.num;
    }

    increase(){
        this.num++;
    }   

}


decorate(TestStrore, {
    id: observable,
    num: observable,
    increase: action
});

> action 은 근데 없어도 된다. 이미 oberbvable 된 상태이고 injection 했기 때문에 컴퍼넌트 전체가 이미 '관찰 대상'이 되었다.

 

function MainView({ navigation, rootStore }) {
    
    const [ numtest, numSet ] = useState(0);
    const testStore = rootStore.getStore('testStore');
    const id = testStore.getID();
    const onPress = useCallback(( e ) => {
        // testStore.changeID(`change${testStore.getNum()}`)
        
        testStore.changeID(`change${testStore.getNum()}`)
        testStore.increase();
    },[ numtest ])
    return (
        <View style={styles.container}> 
            <Text>{id}</Text>
            <Text>{numtest}</Text>
            <Button title="Press Me" onPress={onPress} />
            <Text>gi</Text>
        </View>
    )
}

 

7. react-native-maps

<MapView>

MapView 초반 property 이해하기 좋은 이미지

'FE > React & RN' 카테고리의 다른 글

[ React-Native ] Pixel Density  (0) 2019.11.07
[ React-Native ] Navigation  (0) 2019.11.06
[ React-Native ] 오류,, 경우  (0) 2019.10.29
[ React-native ] 주요 기능  (0) 2019.10.23
[ React-Native ] React 다른점  (0) 2019.10.21

댓글