React-native объединяет redux-persist с локальным и чувствительным хранилищем - PullRequest
1 голос
/ 12 марта 2020

Вот ситуация: я разрабатываю приложение в React Native, в котором я храню данные о соединении (id, токен и логическое значение для автоматического входа в систему c). До этого я без проблем заботился о локальном хранении всего с помощью AsyncStorage.

Затем я попытался настроить избыточное-постоянное-чувствительное хранилище для безопасного хранения токена, чтобы пользователь не мог легко получить к нему доступ, отслеживая через локальные данные.

Я искал в различных документах, например, таких как: - https://github.com/CodingZeal/redux-persist-sensitive-storage - https://github.com/rt2zz/redux-persist#nested -persistsf - https://blog.reactnativecoach.com/the-definitive-guide-to-redux-persist-84738167975

Но я не могу найти случаев, когда разные типы хранилищ используются вместе, и я не могу дать функциональный результат.

Вот мои разные части кода : - Конфигурация моего магазина.

//Store/configureStore.js

import {combineReducers, createStore} from 'redux'
import authenticateReducer from './Reducers/authenticateReducer'
import tokenReducer from './Reducers/tokenReducer';
import { persistReducer } from 'redux-persist'
import createSensitiveStorage from "redux-persist-sensitive-storage"
import AsyncStorage from '@react-native-community/async-storage';



// Si besoin d'un type de stockage classique, voir doc redux-persist-sensitive-storage pour combinaison de plusieurs types de stockages
//Attendre ejction pour utilisation données sécurisées

const sensitiveStorage = createSensitiveStorage({
    keychainService: "myKeychain",
    sharedPreferencesName: "mySharedPrefs"
});

// const mainPersistConfig = {
//     key: 'main',
//     storage: storage
// }

const tokenPersistConfig = {
    key: "tokene",
    storage: sensitiveStorage
}

const authPersistConfig = {
    key: 'auth',
    storage: AsyncStorage
}

const mainReducer = combineReducers({
    main: persistReducer(authPersistConfig, authenticateReducer),
    token: persistReducer(tokenPersistConfig, tokenReducer)
})

export default createStore(mainReducer)
  • Приложение. js
//App.js

import React from 'react';
import Navigation from './Navigation/Navigation'
import {Provider} from 'react-redux'
import Store from './Store/configureStore'
import {persistStore} from 'redux-persist'
import {PersistGate} from 'redux-persist/es/integration/react'

class App extends React.Component{
    render(){
        let persistor = persistStore(Store)
        console.log("store" + JSON.stringify(Store))
        return (
            //Le provider permet de distribuer le Store Redux dans toute l'application
            <Provider store={Store}>
                <PersistGate persistor={persistor}>
                    <Navigation/>
                </PersistGate>
            </Provider>
        )
    }
}

export default App
  • А вот часть, которая подключается к тенту на мой стартовый взгляд. Здесь я запутался в своих попытках и не знаю, как вернуть значение моего токена.

token: state.tokenReducer.token, ou token: state.mainReducer.token, ect ..

//Connexion du state global de l'application
const mapStateToProps = (state) => {
    console.log("state:" +JSON.stringify(state))
    return {
        token: state.tokenReducer.token,
        id: state.authenticateReducer.id,
        autolog: state.authenticateReducer.autolog
    }
}

Небольшая помощь, позволившая мне использовать оба способа хранения, приветствуется!

Большое спасибо.

...