我有关于道具导航的问题,我想知道如果条件为真,我如何导航其他屏幕?我有模块的用户需要登录,我使用的是ReactJS应用编程接口。下一步,我可以在api中获得正确的响应,但是我的if语句中存在问题,即my props is undefined不是一个对象。
我这里有我写的代码,,
AsyncStorage.getItem('authorization_code', (err, result) => {
let token = result;
axios({
method: 'post',
url: 'http://1xx.xx.x.xx:8002/api/auth/me?token=',
headers: {"Authorization" : `Bearer ${token}`}
}).then(response => {
const email = response.data.email;
const user_type = response.data.user_type;
AsyncStorage.setItem('USERMAIL',email.toString());
AsyncStorage.setItem('USERTYPE',user_type.toString());
if(user_type == 1) {
this.props.navigation.push('Dashboard');
}
else if(user_type == 3) {
this.props.navigation.push('Dashboard');
}
})
});
谢谢。
发布于 2019-05-24 08:33:12
这是因为您正在访问另一个closure中的this
。要解决这个问题,您可以存储一个局部变量,并从传递给then
的函数中访问它。一个常见的约定是创建一个名为that
的新变量,其中包含您希望持久化到闭包的this
。
getItemFromStorage() {
// this line is the key
const that = this;
AsyncStorage.getItem('authorization_code', (err, result) => {
let token = result;
axios({
method: 'post',
url: 'http://1xx.xx.x.xx:8002/api/auth/me?token=',
headers: {"Authorization" : `Bearer ${token}`}
}).then(response => {
const email = response.data.email;
const user_type = response.data.user_type;
AsyncStorage.setItem('USERMAIL',email.toString());
AsyncStorage.setItem('USERTYPE',user_type.toString());
// now you can access that to obtain the props
if(user_type == 1) {
that.props.navigation.push('Dashboard');
}
else if(user_type == 3) {
that.props.navigation.push('Dashboard');
}
})
});
}
有关此here的更多信息
https://stackoverflow.com/questions/56284123
复制相似问题