React Native에서 Redux 템플릿 사용

Redux는 JavaScript 앱을위한 예측 가능한 상태 컨테이너입니다.

일관되게 작동하고 다양한 환경 (클라이언트, 서버 및 네이티브)에서 실행되고 테스트하기 쉬운 애플리케이션을 작성하는 데 도움이됩니다. 또한 훌륭한 개발자 경험을 제공합니다.

Unsplash에 Safar Safarov의 사진

설치

반응 네이티브에 redux를 설치하기 위해. 다음 패키지를 설치합니다.

yarn add react-redux redux redux-persist redux-thunk @react-native-community/async-storage
  1. 행위
  2. 감속기
  3. index.js

types.js에 다음 코드를 추가하십시오.

export const SAVE_TOKEN = 'SAVE_TOKEN';

import { SAVE_TOKEN } from './types';
export const saveToken = (key) => ({
  type: SAVE_TOKEN,
  payload: key
});

index.js에 다음 코드를 추가하십시오.

import { SAVE_TOKEN } from '../actions/types';
const initialState = {
 token: ''
};
const Reducer = (state = initialState, action) => {
switch (action.type) {
case SAVE_TOKEN:
 return {
   ...state,
   token: action.payload,
};
default: 
 return state;
}
};
export default Reducer;

import {applyMiddleware, combineReducers, createStore, compose} from 'redux';
import thunk from 'redux-thunk';
import {persistStore, persistReducer} from 'redux-persist';
import AsyncStorage from '@react-native-community/async-storage';
import Reducer from './reducers';
// Redux Debugger
let composeEnhancer = compose;
if (__DEV__) {
composeEnhancer = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
}
const Reducers = {
 appData: Reducer
};
const persistConfig = {
 key: 'root',
 storage: AsyncStorage,
 blacklist: ['navigation'], // navigation will not be persisted
 // stateReconciler: autoMergeLevel2,
 // timeout: 100000,
};
const persistedReducer = persistReducer(
 persistConfig,
 combineReducers(Reducers),
);
export const Store = createStore( 
 persistedReducer,composeEnhancer(applyMiddleware(thunk))
);
export const persistor = persistStore(Store);

App.js 파일에 다음 코드를 추가합니다.

import React from 'react';
import {Route} from './src/navigation/routes';
import {Provider} from 'react-redux';
import {PersistGate} from 'redux-persist/integration/react';
import {Store, persistor} from './src/store';
import {StatusBar} from 'react-native';
import RNBootSplash from 'react-native-bootsplash';
const App = () => {
 RNBootSplash.hide();
 return (
  <Provider store={Store}>
   <PersistGate loading={null} persistor={persistor}>
   <StatusBar backgroundColor="#000" barStyle="light-content" /
    <Route />
   </PersistGate>
  </Provider>
);
};
export default App;

import React, {useState, useEffect} from 'react';
import {persistor} from '../store';
import * as wpActions from '../../store/actions';
import {useSelector, useDispatch} from 'react-redux';
const Login = ({navigation}) => {
 const dispatch = useDispatch();
 const [code, setCode] = useState('');
 const details = useSelector((state) => state.appData.details);
 console.log(details);
// Comment this code if not clearing database.
 useEffect(() => {
  persistor.purge;
  console.log('purging database');
 }, []);
 
 const sendToken=()=>{ 
   dispatch(wpActions.saveToken(code))
 }

yarn add @react-native-community/async-storage @react-native-community/masked-view  @react-navigation/drawer @react-navigation/native @react-navigation/stack react-native-gesture-handler react-native-reanimated react-native-responsive-screen react-native-safe-area-context react-native-screens react-native-vector-icons react-redux redux redux-persist redux-thunk

Suggested posts

배열 매핑에서 "키"의 중요한 역할

배열 매핑에서 "키"의 중요한 역할

React에서 배열을 매핑하는 동안 "각 요소에는 고유한 키가 있어야 합니다"라는 경고 메시지를 무시하는 경향이 있는 사람이라면 먼저 이 경고가 발생하는 이유를 잠시 시간을 내어 이해하는 것이 중요합니다. React에서 “Array.

React Native와 Android 비교: 포괄적인 비교

Android에서 React Native로의 여정

React Native와 Android 비교: 포괄적인 비교

7년 이상의 경력을 가진 Android 개발자로서 저는 항상 Java와 Kotlin의 세계에 끌렸습니다. 하지만 약 1년 전쯤에 저는 새로운 것을 탐구하고 싶다는 생각이 들었습니다. 그때부터 React Native에 뛰어들기 시작했습니다.

Related posts

조던 닐리의 살인과 "애국적" 인종차별의 문제

미국은 인종차별적 행동을 좋은 미국인이 되는 것과 동일시하지 않는 필수적인 조치를 취할 수 있습니까?

조던 닐리의 살인과 "애국적" 인종차별의 문제

[방아쇠 경고: 이 에세이에는 Jordan Neely의 살인자를 칭찬하는 사람들의 스크린 샷이 포함되어 있습니다.] 법 집행관은 마침내 그리고 아마도 마지못해 죽을 때까지 Jordan Neely를 질식시킨 사람인 Daniel Penny를 살인 혐의로 기소했습니다.

작문 실력을 향상시키는 3가지 입증된 방법

글쓰기의 이점과 그렇게 하는 데 도움이 되는 전략

작문 실력을 향상시키는 3가지 입증된 방법

2022년에는 GPT-3가 출시되면서 글쓰기 능력이 덜 중요해진 것 같습니다. AI를 사용하면 글이 서투른 사람들도 양질의 직원을 생성할 수 있습니다.

팟캐스트가 영향력 있는 이유는 무엇입니까?

팟캐스트가 영향력 있는 이유는 무엇입니까?

지난 주에 저는 PressGazette(영국 언론 뉴스 웹사이트)를 통해 발송된 보도 자료를 보았습니다. 이 기사는 Scandi 팟캐스트 호스팅 및 광고 회사인 Acast가 팟캐스팅에서 "아마도 가장 영향력 있는" 게시자 컨소시엄을 이끌 것이라고 발표했습니다.

도메인 이름에 대한 정보 찾기

Brian P. Hogan의 Small, Sharp 소프트웨어 도구에서 발췌

도메인 이름에 대한 정보 찾기

facebook.com에 요청하면 컴퓨터가 도메인 이름을 조회하여 해당 도메인 이름을 IP 주소로 변환하므로 컴퓨터가 해당 연결을 만들 수 있습니다.