我正在尝试在我的抽屉组件中获取AsyncStorage
中的值。我已经完成条件渲染以显示抽屉内的login
和logout
按钮。因此,在成功登录后,如果AsynStorage
中有值,则抽屉内的按钮应为Logout
而不是Login
。但是在打开抽屉后最初打开时,AsyncStorage
的值没有得到。只有当我点击抽屉中的特定项目时才会获得。所以如何在抽屉打开时获取值?我已经完成了以下操作
login.js
async saveItem(item, selectedValue) {
try {
await AsyncStorage.setItem(item, selectedValue);
} catch (error) {
console.error('AsyncStorage error: ' + error.message);
}
}
...
....
...
.then((response) => response.json())
.then((responseData) => {
this.setState({
login: responseData
})
if (responseData.status == true) {
this.saveItem('userdetail', responseData.token.access_token);
this.saveItem('userimage', responseData.user.avatar);
this.saveItem('user', responseData.user.name);
Actions.dashBoard();
this.setState({ isLoading: false });
} else {
....
}
drawer.js
componentDidMount() {
AsyncStorage.getItem("user").then(value => {
this.setState({ name: value })
})
console.log(this.state.name);
}
onPressList = (data, index) => {
AsyncStorage.getItem("user").then(value => {
this.setState({ name: value })
})
if (this.state.name) {
if (data.route == "profile")
Actions.profile();
...
....
...
}
}
render(){
return(
{this.state.name? (
<ListItem
button
noBorder
onPress={() => this.onPressLogout()}
>
<Text style={[styles.text, { textAlign: 'left' }]}>
Logout
</Text>
</ListItem>
) : (
<ListItem
button
noBorder
onPress={() => this.onPressLogin()}
>
<Text style={[styles.text, { textAlign: 'left' }]}>
Login
</Text>
</ListItem>) }
)
}
在每个列表项的抽屉里面我检查是否设置了name
。它只会在name
存在的情况下导航。但问题最初在componentDidMount
内我没有得到AsyncStorage
中的值。请帮我找到解决方案。问题只存在于侧栏。我在其他所有屏幕上都获得了AsyncStorage
的价值。请帮忙。任何帮助都会非常明显。谢谢。
问题是您在将用户添加到异步存储之前检查用户。单击某个项目时它起作用的原因是每次单击列表项时都要检查用户。而不是componentDidMount
你可以使用componentWillUpdate
。我猜测当你点击抽屉时它会更新组件,然后检查用户(因为React重新渲染整个Component子树)。
希望有所帮助
componentWillUpdate() {
AsyncStorage.getItem("user").then(value => {
this.setState({ name: value })
})
console.log(this.state.name);
}