如何在不导航到另一个屏幕的情况下将信息从一个屏幕发送到另一屏幕



我是React Native的新手,我一直在尝试制作一个活动组织者,如果你注册了一个活动,它会被添加到另一个包含你的时间表的页面中。然而,我一直在查看文档,似乎找不到如何在不实际导航到另一个屏幕的情况下将数据从一个屏幕发送到另一屏幕。换句话说,我想要这个navigation.navigate('Schedule', {name: eventName, time: eventTime});,但不需要导航。

以下是一些建议:

1.AsyncStorage:您可以将它们保存到AsyncStorage(这是手机上由硬件支持的安全存储(,并且可以随时检索它们。假设用户的时间表是一系列事件,例如:

var a = [{ name: eventName, time: eventTime }, { name: eventName, time: eventTime }]

您可以这样做:

AsyncStorage.setItem('Schedule', JSON.stringify(a));
AsyncStorage.getItem('Schedule');

请参阅:https://github.com/react-native-community/async-storage

2.后端

将事件保存到后端服务器,然后从其他页面检索它们。

3.Redux或React Hooks(高级(https://medium.com/swlh/react-global-state-with-hooks-f163e49f90f9https://redux.js.org/introduction/getting-started/

4.全局状态w/React Hooks

我最喜欢的内置React Hooks 管理全局状态的新方法

您可以有一个全局对象来存储屏幕之间的共享数据。即使您阅读了Redux文档,redux的使用情况之一是当您有一些数据要在不同的屏幕之间共享时。

这是全局对象(Singleton模式(的代码

export class GlobalState {
public static getInstance(): GlobalState {
if (GlobalState.instance == null) {
GlobalState.instance = new GlobalState()
}
return GlobalState.instance
}
private state: IGlobalState = this.restoreDefaultState()
private restoreDefaultState(): IGlobalState {
return (
{
// your properties are placed here
}
)
}
}

用法:

GlobalState.getInstance() ... //call any function placed there

注意:上面的代码是用TypeScript编写的,您可以很容易地将其转换为JS

相关内容

最新更新