【问题标题】:How to save my JWT Token Globaly using Redux Thunk in React Native?如何在 React Native 中使用 Redux Thunk 保存我的 JWT Token Globaly?
【发布时间】:2019-07-18 17:51:42
【问题描述】:

下面是我使用 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);

【问题讨论】:

  • 你好,如果你能指定你的后端如何与你的前端通信,也许上传服务器/app.js的代码,我可以帮助你:)
  • 我正在使用简单的 fetch() 方法,当我使用我的凭据登录时它会返回我的令牌。
  • 你使用的是 redux saga 还是 redux thunk?你在哪里取?请上传您获取的代码。
  • 只需要存储在redux中吗?还是还有其他的?

标签: react-native authentication redux state redux-thunk


【解决方案1】:

使用 redux-persist 自动同步部分存储: How and where to save the whole redux store using AsyncStorage的副本

【讨论】:

    【解决方案2】:

    我的代码中有一个愚蠢的错误。我忘记在 AsyncStorage 中使用 asyncawait 关键字,这就是它始终为空的原因。

    谢谢

    【讨论】:

      【解决方案3】:

      使用AsyncStorage 将令牌存储在设备上可能比在 Redux 中更好。

      import { AsyncStorage } from 'react-native';
      
      const setToken = async (token) => {
          try {
              await AsyncStorage.setItem('MY_TOKEN', token);
          } catch(e) {
              console.error(e);
          }
      }
      
      const getToken = async () => {
          const token = await AsyncStorage.getItem('MY_TOKEN');
          return token;
      }
      

      编辑:如果您不想使用 async/await,那么您可以将 asyncStorage.js 中的代码更改为如下所示:

      export const getUserToken = () =>
          AsyncStorage.getItem('userToken');
      }
      

      以及要阅读的 profile.js 中的代码:

      class profile extends Component {
          ...
          componentDidMount() {
              getUserToken().then((token) => console.log("TOKEN=" + token));
          }
          ...
      }
      

      【讨论】:

      • 这不会得到redux的好处,例如能够使用 react-redux,能够监听状态并同步请求。
      • @Markus 绝对没有必要过度设计像存储 JWT 这样简单的东西。第一个问题中描述的问题是,当调用getUserToken 时,它返回一个带有undefined 值的Promise,因为该promise 尚未解决。 Async/await 将解决这个问题,而无需为简单的过程添加额外的样板。
      猜你喜欢
      • 2017-11-22
      • 2020-12-01
      • 2022-01-13
      • 2019-08-07
      • 2018-09-10
      • 1970-01-01
      • 2022-06-10
      • 1970-01-01
      • 2019-09-09
      相关资源
      最近更新 更多