我应该如何使用异步存储在新的导航屏幕中显示数据?
我试图为存储中的项目设置状态:
_retrieveData = async () => {
try {
const value = await AsyncStorage.getItem('sightings');
if (value !== null) {
console.log(value);
this.setState({ sightings: JSON.parse(value) });
}
} catch (error) {
console.log(error);
}
}
但是我不确定在哪里设置? ComponentWillMount将加载一次吗?但是,如果我导航回到另一个屏幕,然后又回到必须加载数据的那个屏幕,该怎么办?
还是我认为不使用状态,而是在模板中使用_retrieveData作为变量?
render() {
return (<Container>
<Content>
<List>
{_retrieveData.map(sighting => {
<ListItem>
<Left>
<Text>{sighting.species}</Text>
</Left>
<Body>
<Text>{sighting.timestamp}</Text>
</Body>
<Right>
<Badge success>
<Text>{sighting.counter}</Text>
</Badge>
</Right>
</ListItem>
})}
</List>
</Content>
</Container>
);
}
这是我的导航:
export default (MainScreenNavigator = createBottomTabNavigator(
{
Start: { screen: AddSighting },
Sightings: { screen: Sightings }
},
{
tabBarPosition: "bottom",
tabBarComponent: props => {
return (
<Footer>
<FooterTab>
<Button vertical onPress={() => props.navigation.navigate("Start")}>
<Icon name="apps" />
<Text>Add sightings</Text>
</Button>
<Button
badge
vertical
onPress={() =>
props.navigation.navigate("Sightings", {
onNavigate: this.handleOnNavigate
})
}
>
<Badge>
<Text>2</Text>
</Badge>
<Text>Sightings</Text>
<Icon name="menu" />
</Button>
</FooterTab>
</Footer>
);
}
}
));
我不确定该如何进行反应吗?
答案 0 :(得分:0)
react-navigation
支持adding listeners到屏幕。通过这种方式,您可以更新数据,以重新读取AsyncStorage
addListener -订阅导航生命周期的更新
反应导航向订阅它们的屏幕组件发出事件:
willBlur
-屏幕将无法对焦willFocus
-屏幕将聚焦didFocus
-屏幕聚焦(如果有过渡,则过渡完成)didBlur
-屏幕未聚焦(如果存在过渡,则过渡完成)
文档示例
const didBlurSubscription = this.props.navigation.addListener(
'didBlur',
payload => {
console.debug('didBlur', payload);
}
);
// Remove the listener when you are done
didBlurSubscription.remove();
// Payload
{
action: { type: 'Navigation/COMPLETE_TRANSITION', key: 'StackRouterRoot' },
context: 'id-1518521010538-2:Navigation/COMPLETE_TRANSITION_Root',
lastState: undefined,
state: undefined,
type: 'didBlur',
};