React native 如何在React Native中使用Redux Thunk全局保存我的JWT令牌?

React native 如何在React Native中使用Redux Thunk全局保存我的JWT令牌?,react-native,authentication,redux,state,redux-thunk,React Native,Authentication,Redux,State,Redux Thunk,下面是我使用Redux Thunk保存和获取JWT令牌的代码。但它总是给出空值。我错在哪里 在profile.js文件中,我想得到我保存的令牌,但它总是给我空值。AsyncStorage.setItem和getItem方法中是否存在任何问题 提前感谢:) authAction.js import {PostData} from '../../components/API'; import {GET_TOKEN,SAVE_TOKEN} from '../type'; import {saveUs

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

在profile.js文件中,我想得到我保存的令牌,但它总是给我空值。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);
import React,{Component}来自'React';
从“react native”导入{样式表、视图、文本};
从'react redux'导入{connect};
从“../../utils/asyncStorage”导入{getUserToken};
类概要文件扩展了组件{
静态导航选项={
标题:null,
};
构造函数(){
超级();
}
componentDidMount(){
getUserToken()
console.log(“TOKEN=“+this.props.TOKEN.TOKEN”)
}
_bootstrapAsync=()=>{
};
render(){
返回(
轮廓
);
}
}
常量mapStateToProps=状态=>({
令牌:state.token,
});
const mapDispatchToProps=调度=>({
getUserToken:()=>调度(getUserToken()),
});
导出默认连接(mapStateToProps、mapDispatchToProps)(配置文件);

在设备上存储令牌可能比在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 persist自动同步部分存储:
重复的

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


谢谢

您好,如果您可以指定您的后端如何与前端通信,或许还可以上传服务器/app.js的代码,我想我能帮您:)我使用的是simple fetch()方法,当我使用凭据登录时,它会返回我的令牌。您使用的是redux saga还是redux thunk?你在哪里取?请将代码上传到您提取的位置。是否只要求存储在redux中?或者还有其他东西?这不会得到redux的好处,例如,能够使用react redux,能够监听状态并同步请求。@Markus绝对没有必要过度设计像存储JWT这样简单的东西。初始问题中描述的问题是,当调用
getUserToken
时,它返回一个带有
未定义值的承诺,因为该承诺尚未解决。Async/await将修复该问题,而无需为简单流程添加额外的样板文件。