gpt4 book ai didi

javascript - 使用 react-navigation AppContainer 保持状态

转载 作者:行者123 更新时间:2023-11-29 15:09:17 25 4
gpt4 key购买 nike

我将 react-native 项目的 react-navigation 从 v2.x 更新到 v3.x。对于 v2.x,我在根目录下渲染了这个:

const AppNavigator = createStackNavigator({...})

const App = () => <AppNavigator persistenceKey={"NavigationState"} />;

export default App;

我需要保持状态,这就是我使用 persistenceKey

的原因

对于 react-navigation 的 v3.x,需要一个应用程序容器,但我在弄清楚如何实现相同的状态持久性方面遇到了问题。

这是我的 v3.x 新代码

const AppNavigator = createStackNavigator({...})

const AppContainer = createAppContainer(AppNavigator)

const App = () => <AppContainer />;

export default App;

如何以这种方式持久化状态?

谢谢

编辑:

我已经试过了:

const AppNavigator = createStackNavigator({...})

const persistenceKey = "persistenceKey"
const persistNavigationState = async (navState) => {
try {
await AsyncStorage.setItem(persistenceKey, JSON.stringify(navState))
} catch(err) {
// handle the error according to your needs
}
}
const loadNavigationState = async () => {
const jsonString = await AsyncStorage.getItem(persistenceKey)
return JSON.parse(jsonString)
}

const AppNavigationPersists = () => <AppNavigator
persistNavigationState={persistNavigationState}
loadNavigationState={loadNavigationState}
/>

const AppContainer = createAppContainer(AppNavigationPersists)

export default AppContainer;

但是我得到这个错误:

无法读取未定义的属性“getStateForAction”

最佳答案

您可能需要更新 react-navigation>= 3.10.0 .

根据 react-navigation changelog , 他们现在只支持 persistNavigationStateloadNavigationStatereact-navigation@^3.10 .

您仍然可以使用 persistenceKey在低于 3.10 的版本上.

---编辑---

版本示例 <3.10.0 :

const AppNavigator = createStackNavigator({...})

const App = () => <AppNavigator persistenceKey={"NavigationState"} />;

export default App;

一个版本的示例实现 >= 3.10.0 :

const AppNavigator = createStackNavigator({...});
const persistenceKey = "persistenceKey"
const persistNavigationState = async (navState) => {
try {
await AsyncStorage.setItem(persistenceKey, JSON.stringify(navState))
} catch(err) {
// handle the error according to your needs
}
}
const loadNavigationState = async () => {
const jsonString = await AsyncStorage.getItem(persistenceKey)
return JSON.parse(jsonString)
}

const App = () => <AppNavigator persistNavigationState={persistNavigationState} loadNavigationState={loadNavigationState} />;

关于javascript - 使用 react-navigation AppContainer 保持状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56587246/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com