![](/img/trans.png)
[英]How to move between tab screens in tab navigator in react navigation 5?
[英]React Navigation 5 Tab.Navigator sending token between Tab.Screens
我正在努力将令牌从一个 Tab.Screen 传递到另一个 Tab.screen
我在 Stack.Navigator 中使用 Tab.Navigator
<Stack.Screen name="Auth"/>
组件导航到<Tab.Screen name="Map"/>
并在那里发送令牌:
props.navigation.replace("BottomTabs", {screen: "Map", params: {token: token}});
到目前为止一切都很好,但现在我有两个标签<Tab.Screen name="Map"/>
和<Tab.Screen name="List"/>
。 我需要通过按导航选项卡将令牌从 Map 组件传递到 List 组件。 我不能像以前一样使用 props.navigation.replace/navigate 或类似的东西传递它。
也许有人可以帮助我找到一种将数据在一个选项卡屏幕之间传递到另一个选项卡的正确方法? 谢谢!
您可以将数据存储在 Context 中并获取它。 或者你可以通过 navigate("Route",{param}) 传递数据并通过 route.param 在其他类中获取它。 或者你可以发送数据作为道具。
好的,我发现在我的情况下似乎是最好的解决方案: https : //dev.to/efearas/how-to-usecontext-and-set-value-of-context-in-child-components-in-3-steps -3j9h
我创建上下文文件auth-context.js
:
import React from 'react';
export const AuthContext = React.createContext();
我在App.js
创建令牌钩子并像这样包装它:
import { AuthContext } from "./auth-context.js";
function AppNavigator() {
const [token, setToken] = useState(null);
return (
<AuthContext.Provider value={[token, setToken]}>
<NavigationContainer>
<Stack.Navigator initialRouteName="Auth">
<Stack.Screen
name="BottomTabs"
component={BottomTabs} // this separate navigator has my map and list components and they also get token in this way
/>
<Stack.Screen
name="Auth"
component={Auth}
/>
<Stack.Screen
// other components which I don't want to have in BottomTabs
/>
</Stack.Navigator>
</NavigationContainer>
</AuthContext.Provider>
在我的auth.js
组件中,我setToken
:
import { AuthContext } from "../auth-context.js";
export default function Auth(props) {
const [token, setToken] = useContext(AuthContext);
useEffect(() => {
(async () => {
const token = await AsyncStorage.getItem('token')
if (token)
setToken(token);
props.navigation.replace("BottomTabs", {screen: "Map"});
})()
}, []);
例如,在这里,它尝试从 AsyncStorage 获取令牌,如果是,则将其设置为 Context Hook(如果我可以这样调用),然后导航到 Map 屏幕(位于子 Tab.Navigator 上)。 无论如何,这只是我使用 React Navigation 5 的项目复杂性。:)
设置令牌后,您可以以相同的方式在其他组件中访问它:
import { AuthContext } from "../auth-context.js";
....
const [token, setToken] = useContext(AuthContext);
免责声明:我远非专家,所以我的解决方案可能不是最漂亮的,但它对我有用,我希望我的挣扎的答案也能帮助其他人:)。
如果有人看到什么可以做得更好,请添加您的答案。 谢谢大家!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.