首页 > 解决方案 > 如何在 React Native 中使用 Redux Thunk 保存我的 JWT Token Globaly?

问题描述

下面是我使用 Redux Thunk 保存和获取我的 JWT 令牌的代码。但它总是给我 null。我在哪里错了?

在 profile.js 文件中,我想获取我保存的令牌。但它总是给我 null。AsyncStorage.setItem 和 getItem 方法有什么问题吗?

先感谢您 :)

authAction.js

 import {PostData} from '../../components/API';
import {GET_TOKEN,SAVE_TOKEN} from '../type';
import {saveUserToken} from '../../utils/asyncStorage'

export const authenticate = (request)  => {
        PostData("login",request,'POST')
        .then(response =>{
            if(response.error){
                console.log("Please try again later");
              }else{
                if(response.meta.status=="ok"){
               console.log("SUCCESS : " +response.meta.message);
               saveUserToken(response.data.user.token);
               dispatch({type: SAVE_TOKEN,payload:response.data.user.token})
              }else{
                console.log("MESSAGE : " +response.meta.message);
              }
        }
        }).catch(error => {
          console.log("ERROR : " +error);
      })
}

authReducer.js

   import  {GET_TOKEN,SAVE_TOKEN} from '../type';

   const initialState = {
    token : null,
   };

  export default (state = initialState, action) =>{
    switch(action.type){
        case GET_TOKEN:
            return { ...state, token: action.token };
        case SAVE_TOKEN:
            return {...state,token:action.token} ;
        default :
            return state;
    }
  };

asyncStorage.js

 import { AsyncStorage } from 'react-native';
 import {GET_TOKEN,SAVE_TOKEN} from '../redux/type';

    export const saveToken = token => ({
        type: SAVE_TOKEN,
        token
    });
    export const getUserToken = () => {
        return AsyncStorage.getItem('userToken')
            .then((data) => {
                console.log("GET TOKEN : " +data);
                // dispatch({type: GET_TOKEN,payload:data})
            })
    }

    export const saveUserToken = (response) => {
          AsyncStorage.setItem('userToken',JSON.stringify(response))
            .then((data) => {
                alert("SAVE TOKEN = " + JSON.stringify(response)); 
            })
    }

profile.js

    import React, { Component } from 'react';
import {StyleSheet,View,Text} from 'react-native';
import { connect } from 'react-redux';
import { getUserToken } from '../../utils/asyncStorage';

class profile extends Component {
    static navigationOptions = {
        header: null,
    };
    constructor() {
        super();
    }
    componentDidMount() {
        getUserToken()
        console.log("TOKEN=" +this.props.token.token)
    }
    _bootstrapAsync = () => {
    };
render() {
  return (
    <View style={ styles.container }>
       <Text onPress={this._bootstrapAsync()}>PROFILE </Text>

    </View>
    );
  }
}

const mapStateToProps = state => ({
    token: state.token,
});


const mapDispatchToProps = dispatch => ({
    getUserToken: () => dispatch(getUserToken()),
});

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

标签: react-nativeauthenticationreduxstateredux-thunk

解决方案


使用 redux-persist 自动同步部分存储:重复使用 AsyncStorage 保存整个 redux 存储的方式和位置


推荐阅读