我对React Native还是很陌生,我一直在尝试创建一个事件组织者,如果您注册一个事件,它将被添加到包含日程安排的另一个页面中。但是,我一直在浏览文档,似乎无法找到如何在不实际导航到另一屏幕的情况下将数据从一个屏幕发送到另一屏幕的方法。换句话说,我想要这个navigation.navigate('Schedule', {name: eventName, time: eventTime});
,但无需导航。
答案 0 :(得分:2)
以下是一些建议:
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-f163e49f90f9 https://redux.js.org/introduction/getting-started/
4。带状态挂钩的全局状态
My new favorite way to manage global state with built-in React Hooks
答案 1 :(得分:0)
您可以有一个全局对象来存储屏幕之间的共享数据。即使您阅读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
。