로메오의 블로그

[React Native] Redux toolkit 본문

Frontend/React

[React Native] Redux toolkit

romeoh 2022. 11. 8. 14:31
반응형

React 목록

 

설치

$ npm install @reduxjs/toolkit

 

 

counter.ts

$ mkdir src/redux
$ touch src/redux/counter.ts
import {createSlice} from '@reduxjs/toolkit';
import type {PayloadAction} from '@reduxjs/toolkit';

export interface CounterState {
  count: number;
}

const initialState: CounterState = {
  count: 0,
};

export const counterSlice = createSlice({
  name: 'counter',
  initialState,
  reducers: {
    increment: state => {
      state.count += 1;
    },
    decrement: state => {
      state.count -= 1;
    },
    incrementByAmount: (state, action: PayloadAction<number>) => {
      state.count += action.payload;
    },
  },
});

export const {increment, decrement, incrementByAmount} = counterSlice.actions;
export default counterSlice.reducer;

 

 

 

 

 

store.ts

$ touch src/redux/store.ts
import {configureStore} from '@reduxjs/toolkit';
import counterReducer from './counter';

export const store = configureStore({
  reducer: counterReducer,
});

export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;

 

 

 

App.tsx

import React from 'react';
import {View, StyleSheet} from 'react-native';
import {store} from './src/redux/store';
import {Provider} from 'react-redux';
import HomeScreen from './src/screens/HomeScreen';

const App = () => {
  return (
    <Provider store={store}>
      <View style={styles.container}>
        <HomeScreen />
      </View>
    </Provider>
  );
};

export default App;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: 100,
  },
});

 

 

 

 

HomeScreen.tsx

import React from 'react';
import {View, Button, Text} from 'react-native';
import type {RootState} from '../redux/store';
import {useSelector, useDispatch} from 'react-redux';
import {decrement, increment, incrementByAmount} from '../redux/counter';

function App() {
  const count = useSelector((state: RootState) => state.count);
  const dispatch = useDispatch();

  return (
    <View>
      <Button
        title="Increment"
        aria-label="Increment value"
        onPress={() => dispatch(increment())}
      />
      <Button
        aria-label="Decrement value"
        title="Decrement"
        onPress={() => dispatch(decrement())}
      />
      <Button
        aria-label="Decrement value"
        title="incrementByAmount"
        onPress={() => dispatch(incrementByAmount(10))}
      />
      <Text>{count}</Text>
    </View>
  );
}

export default App;

 

 

 

 

 

 

 

 

 

 

React 목록

반응형

'Frontend > React' 카테고리의 다른 글

[React Native] Redux toolkit & Todo App  (2) 2022.11.12
[React Native] Redux toolkit & Network call  (0) 2022.11.09
[React Native] Draggable FlatList  (0) 2022.10.24
[React Native] props  (0) 2022.10.20
[React Native] custom font 설정  (0) 2022.10.17
Comments