React Native: AsyncStorage returning the value [object Objec



我正在尝试登录我的API,保存令牌并转到下一页。因此,我决定使用 AsyncStorage 来保存令牌,然后发送标头中的令牌以获取数据。请参阅登录.js类:

登录.js

export default class Login extends React.Component {
constructor (props) {
super (props);
this.state = { tokenValue: '' }
}  
updateTokenValue= (tv) => { this.setState({tokenValue : tv}); }
async saveToken() {
try { await AsyncStorage.setItem('tokenvalue', this.updateTokenValue(this.state.tokenValue)); } 
catch (error) { console.error('[APIREQUEST] AsyncStorage error: ' + error.message); }
}
onLogin() {
axios.post('http://my-api-url/login', {
'credential': this.state.txtInputUser,
'password': this.state.txtInputPassword
})
.then((response) => {        
if(response.status != 200){
Alert.alert('ERROR’, ‘USER or PASSWORD INVALIDATE’);
} else {
console.log("Login success”);
console.log(response.data.token+" | Status: "+response.status); 
saveToken(response.data.token); 
//   open the next screen
Actions.searchproduct ({
userID: 0,
});  
}
})
.catch(function (error) {
console.log('Error: '+error)
return;
});
}
render() {
return (
<View style={styles.container}>      
<TextInput style={styles.inputFields} value={'mobi-dev@blendmobi.com'} onChangeText={txtInputUser => this.setState({txtInputUser})} placeholder={'Usuário'} placeholderTextColor={'#9E9E9E'}/>
<TextInput style={styles.inputFields} value={'Blend@03'} onChangeText={txtInputPassword => this.setState({txtInputPassword})} placeholder={'Senha'} placeholderTextColor={'#9E9E9E'}/>           
<MyButton w="100%" h={55} mt={5} as="stretch" so={0.1} ai="center" bg="#212121" tc="#F5F5F5" fs={22} t="LOGIN" onPress={() => this.onLogin()}/>
</View>
</View>
);
}
}

和我的搜索产品类:

搜索产品.js

//  imports
export default class SearchProduct extends React.Component {
constructor(props) {
super(props);
this.state = { tokenValue: '', };
}
getTokenValue= (tv) => { this.setState({tokenValue : tv}); }
componentDidMount() {
var valueToken = '';
try{
const token = AsyncStorage.getItem('tokenvalue');
if (token != null) {
valueToken = token;
console.log('[SEARCHPRODUCT] Token saved: '+valueToken);
} else {
console.log('[SEARCHPRODUCT] Token empty’);
}
} catch(error) {
console.log('[SEARCHPRODUCT] ERROR TO GET THE TOKEN: '+error);
}
axios.get('http://my-api-url/listdata’, {
headers: {
Authorization: 'Bearer '.concat(valueToken)
},
})
.then((response) => {
console.log(response);
})
.catch((e) => {
console.log('ERROR TO SYNC: '+e)
});
}
//  …
}

在浏览器的控制台中,返回给我的数据是:[对象对象]OBS:这是返回给我的 JSON 模型:

{
"id": "5b048159952a12c06c1d4305",
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoiYmFja29mZmljZSIsImRlbGV0ZWQiOmZhbHNlLCJ1cGRhdGVkQXQiOiIyMDE4LTA1LTI4VDAwOjM4OjM2LjEzN1oiLCJfaWQiOiI1YjA0ODE1OTk1MmExMmMwNmMxZDQzMDUiLCJuYW1lIjoiTW9iaSIsInN1cm5hbWUiOiJEZXYiLCJlbWFpbCI6Im1vYmktZGV2QGJsZW5kbW9iaS5jb20iLCJfc3RvcmVJZCI6IjVhZjQ2MDRlMzMxZTBhMjRjNDM3YWE0ZSIsImlhdCI6MTUyNzQ2NzkxNn0.Yb-ImCWAzv88wtQE65p1Ejv7q8n4rmGsmIsj_DCiSfI"
}

您可以更改 saveToken 函数,如下所示

async saveToken() {
try { 
await this.updateTokenValue(this.state.tokenValue);
await AsyncStorage.setItem('tokenvalue', this.state.tokenValue); 
} 
catch (error)
{ 
console.error('[APIREQUEST] AsyncStorage error: ' + error.message); 
}
}

相关内容

最新更新