React Native iOS端AsyncStorage返回[object Object]问题求助
我帮你排查了代码里的几个关键问题,正是这些导致你拿到[object Object]的token结果,下面一步步给你说明修复方案:
核心问题1:异步操作未正确处理,拿到的是Promise对象
AsyncStorage.getItem()是异步方法,返回的是Promise实例,不是直接的token字符串。你在SearchProduct.js的componentDidMount里直接同步赋值const token = AsyncStorage.getItem('tokenvalue'),此时token是一个Promise对象,转换成字符串就会显示[object Object]。
修复代码(SearchProduct.js)
把componentDidMount改成异步函数,用await获取真实的token值:
async componentDidMount() { try{ const token = await AsyncStorage.getItem('tokenvalue'); if (token != null) { console.log('[SEARCHPRODUCT] Token saved: '+token); // 确保拿到token后再发起请求 axios.get('http://my-api-url/listdata', { headers: { Authorization: `Bearer ${token}` // 用模板字符串更简洁 }, }) .then((response) => { console.log(response); }) .catch((e) => { console.log('ERROR TO SYNC: '+e) }); } else { console.log('[SEARCHPRODUCT] Token empty'); } } catch(error) { console.log('[SEARCHPRODUCT] ERROR TO GET THE TOKEN: '+error); } }
问题2:Login.js中saveToken函数的逻辑错误
你的saveToken函数有3个明显问题:
- 函数定义未接收参数,但调用时传了
response.data.token,完全没用到传入的token值; - 错误地把
this.updateTokenValue(this.state.tokenValue)作为存储值,而这个函数只是用来更新state,没有返回值,相当于存了undefined; - 调用
saveToken时没加this(类方法必须通过this.调用),也没加await,可能token还没存完就跳转到下一页了。
修复代码(Login.js)
// 修正saveToken,直接接收token参数存储 async saveToken(token) { try { await AsyncStorage.setItem('tokenvalue', token); // 如果需要同步更新state,在这里直接处理 this.setState({ tokenValue: token }); } catch (error) { console.error('[APIREQUEST] AsyncStorage error: ' + error.message); } } // 把onLogin改成async函数,以便await保存token的操作 onLogin = async () => { axios.post('http://my-api-url/login', { 'credential': this.state.txtInputUser, 'password': this.state.txtInputPassword }) .then(async (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); // 调用类方法要加this,await确保token存储完成再跳转 await this.saveToken(response.data.token); Actions.searchproduct ({ userID: 0, }); } }) .catch(function (error) { console.log('Error: '+error) return; }); }
额外优化建议
- 可以删掉
updateTokenValue和getTokenValue这两个冗余函数,直接在需要的地方用this.setState更新state; - 登录请求的状态判断建议结合
response.data里的业务标识(比如response.data.success),而不仅仅依赖HTTP状态码; - 给AsyncStorage的key定义一个常量(比如
const STORAGE_KEY_TOKEN = 'tokenvalue'),避免拼写错误。
内容的提问来源于stack exchange,提问作者Wallace Blend
相关产品推荐
相关产品推荐

