javascript - How to handle props navigation inside of if condition using React Native
问题描述
I have question regarding on props navigation, I was wondering how can i navigate other screen if condition is true? I have module where the user need to login, I am using ReactJS api. Moving forward, I can get the right response in the api, however there is problem on my if statement that my props is undefined is not an object.
I have here my codes that I made,
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');
}
})
});
Thanks.
解决方案
这是因为您正在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');
}
})
});
}
更多关于这里
推荐阅读
- python - 如何在python中查找每n(50)行的模式?
- json - 将 JSON 解析为表格(Wordpress)
- python - 使用 PYTHON 3.5 和 Backtrader 使用 GPU 运行优化过程
- php - WordPress 自定义主题将转到 404.php
- javascript - Apollo 查询返回错误“预期字符串,找到字符串”
- python - Allure-behave 不将失败的西装报告为“失败”
- javascript - 如何设置完整的日历以显示下个月
- android - 从接收器设置时 setAlarmClock 不起作用
- django - 无法在 Windows 8.1 机器上激活 Conda 虚拟环境
- php - 使用浮动选项 mpdf 在同一页面上的 div