react-native - 如何在 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);
解决方案
使用 redux-persist 自动同步部分存储:重复使用 AsyncStorage 保存整个 redux 存储的方式和位置
推荐阅读
- r - lpsolve/lpsolveAPI 包中是否有一个函数能够删除未满足的约束(在不可行的情况下)?
- typescript - 打字稿防止对超类型的断言
- kotlin - 如何创建 ArgumentMatchers.any(类型:类
) 在 Kotlin 中进行测试? - python - 从 MongoDB 访问嵌套对象值
- python - 在 Django Html 模板中制作音板时遇到问题
- python - 将轴标题添加到 3d 曲面图袖扣和 plotly
- .net-core - 有没有办法为 .NET Core 搭建脚手架测试?
- android - 此商家未启用 google pay
- node.js - 未使用 regedit 将值设置为注册表
- java - jOOQ:从外键获取引用表