Redux

리덕스 사용예제 2

Machine_웅 2020. 8. 15. 18:26
728x90
반응형

App.js


import React, { Component } from 'react';
import {
  SafeAreaView,
  StyleSheet,
  ScrollView,
  View,
  Text,
  StatusBar,
} from 'react-native';

import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';

import Home from './src/Home' 
import Native_Module from './src/Native_Module'
import UI_Test from './src/UI_Test'
import ReduxSample from './src/ReduxSample'

import { createStore, } from "redux";
import rootReducer from './src/redux/rootReducer'
import {Provider} from "react-redux"


// 스토어 생성 및 리듀서 등록 
const store = createStore(rootReducer);

/* 
// 미들웨어가 있는 경우
const store = createStore( 
  reducers,
  applyMiddleware(
      // Middleware will not be applied to this sample.
  ), 
); */

const Stack = createStackNavigator();

class App extends Component{

  render(){
    return(
      <Provider store={store}>
        <NavigationContainer>
          <Stack.Navigator>
            <Stack.Screen name="Home" component={Home} options={{ headerShown: false }} />
            <Stack.Screen name="Native_Module" component={Native_Module} options={{ headerShown: false }} />
            <Stack.Screen name="UI_Test" component={UI_Test} options={{ headerShown: false }} />
            <Stack.Screen name="ReduxSample" component={ReduxSample} options={{ headerShown: false }} />
          </Stack.Navigator>
        </NavigationContainer>
      </Provider>
   
    )
  }
}

export default App;

1)  스토어를 만들어서  리듀서를 등록해준다.

2) Provider 에 스토어를 등록해주고 사용한 컨테이너를 감싸준다.

3) 미들 웨어가 있는 경우 , 스토어 생성시  등록해 준다.

 

 rootReducer.js

import { TOGGLE_SWITCH,INCREMENT, DECREMENT } from "./actionType";


// 초깃값 설정
const initialState = {
    light: false,
    counter: 0
};

function rootReducer(state = initialState, action) {

    switch (action.type) {
        case TOGGLE_SWITCH:
            return {
                ...state, // 기존의 값은 그대로 두면서
                light: !state.light // light 값 반전시키기
            };
        case INCREMENT:
            return {
                ...state,
                counter: state.counter + action.data
            };
        case DECREMENT:
            return {
                ...state,
                counter: state.counter - 1
            };
        default:
            // 지원하지 않는 액션의 경우 상태 유지
            return state;
    }

}

export default rootReducer;

 

actionType.js

export const TOGGLE_SWITCH = "TOGGLE_SWITCH";

export const INCREMENT = "INCREMENT";

export const DECREMENT = "DECREMENT";

리듀서와 액션에서  사용할 action의 이름을 정해준다.

 

action.js

import { TOGGLE_SWITCH,INCREMENT, DECREMENT } from "./actionType";

export function addArticle(payload) {

    return { type: "ADD_ARTICLE", payload }

};

export function addTodo(data) {
    return {
      type: "ADD_TODO",
      data
    };
  }

export function toggleSwitch(){
    return {
        type : TOGGLE_SWITCH
    }
}

export function increment( data ){
    return {
        type : INCREMENT,
        data : data,
    }
}

export function decrement(){
    return {
        type : DECREMENT
    }
}

 

ReduxSample.js

 

import { connect } from 'react-redux';
import React,{ Component } from 'react';

import {
    SafeAreaView,
    StyleSheet,
    ScrollView,
    View,
    Text,
    StatusBar,
    TouchableOpacity
  } from 'react-native';


import {increment,decrement} from './redux/action'

class ReduxSample extends Component{
    constructor(props){
        super(props)

    }


    render(){
        return(
            <View  style= {{ flex:1, justifyContent:'center',alignItems:'center'}}> 

                <Text>
                    리덕스 샘플
                </Text>

                <TouchableOpacity
                    style= {{height:50, width:100, backgroundColor:'white',justifyContent:'center',alignItems:'center'}}
                    onPress = {()=> this.props.increse_data(1)}
                >
                    <Text> 증가 ! </Text>
                    <Text>{this.props.counter}</Text>
                </TouchableOpacity>

                <TouchableOpacity
                    style= {{height:50, width:100, backgroundColor:'white',justifyContent:'center',alignItems:'center'}}
                    onPress = {()=> this.props.decrese_data()}
                >
                    <Text> 감소 ! </Text>
                </TouchableOpacity>
                

            </View>
        )
    }
}



function mapStateToProps(state) {
    // 리듀서 안에 있는 state를 리턴해 온다.
    return {
        light: state.light,
        counter: state.counter
    };
}

function mapDispatchToProps(dispatch) {
    // action을 이용하여, 리듀서 내부의 함수를 호출해  데이터를 조작한다.
    return {
        increse_data:(data) => {
            dispatch(increment(data));
        },
        decrese_data:() => {
            dispatch(decrement());
        }
    };
}

export default connect(mapStateToProps, mapDispatchToProps)(ReduxSample);

 

 

 

 

 

728x90
반응형

'Redux' 카테고리의 다른 글

redux 사용예제 ( feat. useSelector / useDispatch )  (0) 2022.10.11
리덕스 사용예제 1  (0) 2020.08.15
Redux 업데이트  (0) 2020.08.15
리덕스란  (0) 2020.01.29