在 React Native 中使用 mobx 进行状态存储时无法导航到不同的导航菜单

2024-02-29

我对 Mobx 有点陌生,一般来说,我的反应是原生的, 我正在尝试使用 mobx 在导航堆栈中实现状态值更改,以便当单击登录按钮时,状态中的值会发生更改,并且导航值参数令牌会更新为 mobx 存储中的最新值 但这不起作用

我收到错误错误任何导航器均未处理有效负载 {"name":"dashboard"} 的操作“NAVIGATE”。 请建议我实时更改 mobx 存储数据的值并导航的最佳方法

在导航中更改后,如何使用 useselector 从商店获取状态值

请参阅下面的登录屏幕代码

import React, { FC, useState } from "react"
import {
  View,
  ViewStyle,
  TextStyle,
  ImageStyle,
  SafeAreaView,
  TouchableOpacity,
  TextInput,
  ImageBackground,
  KeyboardAvoidingView,
  Platform,
} from "react-native"
import { StackScreenProps } from "@react-navigation/stack"
import { observer } from "mobx-react-lite"
import {
  Button,
  Header,
  Screen,
  Text,
  GradientBackground,
  AutoImage as Image,
} from "../../components"
import { color, spacing, typography } from "../../theme"
import { NavigatorParamList } from "../../navigators"
import { useTokenStore } from "../../utils/storage"


const wragbyLogo = require("./logo.png")
const ScreenBg = require("./bg.png")

const FULL: ViewStyle = { flex: 1 }
const CONTAINER: ViewStyle = {
  backgroundColor: color.transparent,
  paddingHorizontal: spacing[4],
}
const TEXT: TextStyle = {
  color: color.palette.white,
  fontFamily: typography.primary,
}
const BOLD: TextStyle = { fontWeight: "bold" }

const CONTAIN: TextStyle = {
  padding: 20,
  flex: 1,
}

const ALMOST: TextStyle = {
  ...TEXT,
  ...BOLD,
  fontSize: 26,
  fontStyle: "italic",
}

const HOME_LOGO: ImageStyle = {
  alignSelf: "center",
  marginVertical: spacing[5],
  maxWidth: "100%",
  marginTop: 100,
  width: 200,
  height: 60,
}
const CONTENT: TextStyle = {
  ...TEXT,
  color: "#BAB6C8",
  fontSize: 15,
  lineHeight: 22,
  marginBottom: spacing[5],
}

const TEXT_INPUT: TextStyle = {
  ...TEXT,
  backgroundColor: "#fff",
  marginTop: 10,
  marginLeft: 10,
  marginRight: 20,
  borderWidth: 2,
  borderColor: "lightblue",
  fontSize: 12,
  padding: 10,
  borderRadius: 8,
  height: 50,
  color: "#20162D",
  lineHeight: 22,
  marginBottom: spacing[1],
}
const TEXT_INPUT_END: TextStyle = {
  ...TEXT,
  backgroundColor: "#fff",
  marginTop: 10,
  marginLeft: 10,
  marginRight: 20,
  borderWidth: 2,
  borderColor: "lightblue",
  fontSize: 12,
  padding: 10,
  borderRadius: 8,
  height: 50,
  color: "#20162D",
  lineHeight: 22,
}
const CONTINUE: ViewStyle = {
  paddingVertical: spacing[4],
  paddingHorizontal: spacing[4],
  backgroundColor: "#051C5C",
}
const LOGO_TEXT: ViewStyle = {
  alignItems: "center",
  justifyContent: "center",
  paddingHorizontal: spacing[4],
  marginBottom: 100,
}
const CONTINUE_TEXT: TextStyle = {
  ...TEXT,
  ...BOLD,
  fontSize: 13,
  letterSpacing: 2,
}

const BLUE_TEXT: TextStyle = {
  ...TEXT,
  ...BOLD,
  color: "#00F",
}
const ACTION_LINK: TextStyle = {
  ...TEXT,
  ...BOLD,
  flexDirection: "row",
  marginTop: 25,
  alignItems: "center",
  justifyContent: "center",
  letterSpacing: 2,
}

const FOOTER_CONTENT: ViewStyle = {
  paddingVertical: spacing[4],
  paddingHorizontal: spacing[4],
}

const BOTTOM_HALF: ViewStyle = {
  flex: 1,
  padding: 30,
  borderWidth: 4,
  borderTopLeftRadius: 20,
  borderTopRightRadius: 20,
  borderColor: "#fff",
  backgroundColor: "#fff",
}
const LABEL: TextStyle = {
  marginTop: 30,
  color: "#000",
}
const NORMAL_TEXT: TextStyle = {
  color: "#000",
  marginTop: 5,
}
const RED_TEXT: TextStyle = {
  color: "#f00",
  textAlign: "right",
}
const RED_ACTION_LINK: TextStyle = {
  ...TEXT,
  ...BOLD,
  marginTop: 10,
  marginBottom: 10,
  marginRight: 20,
}
const SUBJECT: TextStyle = {
  fontWeight: "bold",
  color: "#000",
  fontSize: 20,
}
const KEYBOARD: TextStyle = {
  flex: 1,
}

export const LoginScreen: FC<StackScreenProps<NavigatorParamList, "login">> = observer(
  ({ navigation }) => {
    const { setToken } = useTokenStore(); 


    const showDashboard = () => {
     const newtokenBool =  setToken();
     console.log("newtokenBool >> "+ newtokenBool)

      navigation.navigate("dashboard")
    }
    const [loading, setLoading] = useState(false)
    const [email, setEmail] = useState("")
    const [password, setPassword] = useState("")
    // const [username, setUsername] = useState('[email protected] /cdn-cgi/l/email-protection');
    // const [password, setPassword] = useState('Password123');

    return (
      <ImageBackground source={ScreenBg} style={FULL}>
        <Image source={wragbyLogo} style={HOME_LOGO} />
        <View style={LOGO_TEXT}>
          <Text>powered by SAP...</Text>
        </View>
        <View style={BOTTOM_HALF}>
          <SafeAreaView>
                <Text style={SUBJECT}>Login</Text>
                <Text style={LABEL}>Email</Text>

                <TextInput
                  style={TEXT_INPUT}
                  placeholderTextColor="#D8D8D8"
                  onChangeText={(email) => setEmail(email)}
                  placeholder=""
                  autoCapitalize="none"
                  value={email}
                />
                <Text style={LABEL}>Password</Text>

                <TextInput
                  style={TEXT_INPUT_END}
                  placeholderTextColor="#D8D8D8"
                  onChangeText={(password) => setPassword(password)}
                  secureTextEntry={true}
                  placeholder=""
                  autoCapitalize="none"
                  value={password}
                />

                <View style={RED_ACTION_LINK}>
                  <TouchableOpacity onPress={() => navigation.navigate("resetpassword")}>
                    <Text style={RED_TEXT}>Forgot Password</Text>
                  </TouchableOpacity>
                </View>

                <View style={FOOTER_CONTENT}>
                  <Button
                    testID="next-screen-button"
                    style={CONTINUE}
                    textStyle={CONTINUE_TEXT}
                    tx="welcomeScreen.signIn"
                    onPress={showDashboard}
                  />
                  <TouchableOpacity onPress={() => navigation.navigate("signup")}>
                    <Text style={NORMAL_TEXT}>
                      Don't have an Account yet? <Text style={BLUE_TEXT}>Sign up</Text>
                    </Text>
                  </TouchableOpacity>
                </View>
     
          </SafeAreaView>
        </View>
      </ImageBackground>
    )
  },
)

//------------------------- 看下面的导航

import React, { useEffect } from "react"
import { useColorScheme } from "react-native"
import { NavigationContainer, DefaultTheme, DarkTheme } from "@react-navigation/native"
import { createNativeStackNavigator } from "@react-navigation/native-stack"
import {
  WelcomeScreen,
  DemoScreen,
  DemoListScreen,
  SignupScreen,
  LoginScreen,
  ResetPasswordScreen,
  DashboardScreen,
  HomeScreen,
  ArticleScreen,
} from "../screens"
import { navigationRef } from "./navigation-utilities"
import { useTokenStore, TokenStoreContext } from "../utils/storage/token"

/**
 * This type allows TypeScript to know what routes are defined in this navigator
 * as well as what properties (if any) they might take when navigating to them.
 *
 * If no params are allowed, pass through `undefined`. Generally speaking, we
 * recommend using your MobX-State-Tree store(s) to keep application state
 * rather than passing state through navigation params.
 *
 * For more information, see this documentation:
 *   https://reactnavigation.org/docs/params/
 *   https://reactnavigation.org/docs/typescript#type-checking-the-navigator
 */
export type NavigatorParamList = {
  welcome: undefined
  demo: undefined
  demoList: undefined
  login: undefined
  signup: undefined
  resetpassword: undefined
  dashboard: undefined
  home: undefined
}

// Documentation: https://reactnavigation.org/docs/stack-navigator/
const Stack = createNativeStackNavigator<NavigatorParamList>()

const AppStack = () => {
  const { getToken } = useTokenStore()
  const [userToken, setUserToken] = React.useState(false)

  useEffect(() => {
    console.log("<<<<< IS LOGGED IN STATE >>>>>>")
    console.log(userToken)
    console.log("<<<<< IS LOGGED IN STATE >>>>>>")
    setUserToken(getToken())
    console.log("<<<<< NEW TOKEN IN STATE >>>>>>")
    console.log(userToken)
    console.log("<<<<< NEW TOKEN IN STATE >>>>>>")
  }, [userToken])

  return (
    <Stack.Navigator
      screenOptions={{
        headerShown: false,
      }}
      initialRouteName="login"
    >
      {!userToken ? (
        <>
          <Stack.Screen name="login" component={LoginScreen} />
          <Stack.Screen name="signup" component={SignupScreen} />
          <Stack.Screen name="resetpassword" component={ResetPasswordScreen} />
          <Stack.Screen name="demo" component={DemoScreen} />
          <Stack.Screen name="demoList" component={DemoListScreen} />
          <Stack.Screen name="welcome" component={WelcomeScreen} />
        </>
      ) : (
        <>
          <Stack.Screen name="dashboard" component={DashboardScreen} />
        </>
      )}
    </Stack.Navigator>
  )
}

interface NavigationProps extends Partial<React.ComponentProps<typeof NavigationContainer>> {}

export const AppNavigator = (props: NavigationProps) => {
  const colorScheme = useColorScheme()
  return (
    <NavigationContainer
      ref={navigationRef}
      theme={colorScheme === "dark" ? DarkTheme : DefaultTheme}
      {...props}
    >
      <AppStack />
    </NavigationContainer>
  )
}

AppNavigator.displayName = "AppNavigator"

/**
 * A list of routes from which we're allowed to leave the app when
 * the user presses the back button on Android.
 *
 * Anything not on this list will be a standard `back` action in
 * react-navigation.
 *
 * `canExit` is used in ./app/app.tsx in the `useBackButtonHandler` hook.
 */
const exitRoutes = ["welcome"]
export const canExit = (routeName: string) => exitRoutes.includes(routeName)

//------------------------------------ 下面是我的 mobx 存储文件

import { action, computed, makeObservable, observable } from "mobx";
import React from "react";

class TokenValue{
    token = false;
    constructor() {
        makeObservable(this, {
            token: observable,
            getToken: action,
            unsetToken: action,
            setToken: action
        })
      }

    setToken(){
        this.token = true;
    }

    unsetToken(){
        this.token = false;
    }

    getToken(){
        if(this.token === undefined)
            {
                return false;
            }else{
                return true;
            }
    }

}

 const tokenValueStore = new TokenValue();

 export const TokenStoreContext = React.createContext(tokenValueStore);
 export const useTokenStore = () => React.useContext(TokenStoreContext)

我最终使用了react-redux而不是mobx,因为mobx不允许使用useSelector和Dispatch

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 React Native 中使用 mobx 进行状态存储时无法导航到不同的导航菜单 的相关文章

随机推荐

  • 最新SDK的SDKROOT路径

    我正在使用 Xcode 构建旧代码并指定SDKROOT Developer SDKs MacOSX HOST VERSION sdk 我想为系统上预安装 的最新 SDK 指定 SDKROOT 例如我在10 8已经并且我想指定SDKROOT与
  • 未加权无向图中的最长路径

    以此图作为参考 假设我想要 0 到 5 之间的最长路径 那将是 0 gt 1 gt 3 gt 2 gt 4 gt 6 gt 5 有什么好的算法吗 我已经搜索过 但没有找到任何我能理解的东西 我发现了很多最短路径的算法 0 gt 1 gt 2
  • Python:Struct.pack(format, [...]),虽然格式几乎相同,但打包数据的大小不同

    import struct data struct pack ici 1 chr 1 1 print len data 12 data struct pack iic 1 1 chr 1 print len data 9 两个 data 变
  • 连接 MongoDB Atlas 与 Mongoose 时出现超时错误

    我正在尝试使用 mongoose 连接到 MongoDB Atlas 上的数据库 但每次它都会给我以下错误 node 2327 UnhandledPromiseRejectionWarning Error queryTxt ETIMEOUT
  • 密码和不同类型的加密

    我知道 我知道 类似的问题已经被问过数百万次了 但由于大多数问题都有不同的风格 所以我有自己的风格 目前我正在开发一个网站 该网站打算在全国范围内推出 因此需要对用户系统进行某种保护 我最近读了很多关于密码加密 散列 加盐 凡是你能想到的内
  • ios:使用 GLEssentials 示例代码显示简单的 3D 模型

    我的目标是显示一个简单的 3D 模型并在其上应用纹理 我已经下载了 GLEssentialsios示例项目 http developer apple com library ios samplecode GLEssentials Intro
  • 删除 SimpleForm 生成的选择字段的空白选项

    我有这段代码 f input category as gt select label gt false collection gt Choices Categories Choices Categories 只是 key gt value
  • 使用 TCP 的模拟器连接

    又嗨了 我正在尝试连接在同一台 PC 上作为服务器和客户端运行的两个模拟器 问题是其中一个位于虚拟机内 每个模拟器应该使用什么地址才能在它们之间进行连接 我正在使用基于 TCP 的连接 第一个模拟器在 Windows 7 上运行 Vmwar
  • 适用于高带宽应用的 WebRTC 数据通道

    我想通过 WebRTC 数据通道发送单向流数据 并且正在寻找最佳配置选项 高带宽 低延迟 抖动 以及其他人在此类应用程序中的预期比特率的经验 我的测试程序发送 2k 的块 使用 2k 的 bufferedAmountLowThreshold
  • 找不到 ID 为“xxx”的 UpdatePanel。如果它是动态更新的,那么它必须位于另一个 UpdatePanel 内

    我有一个带有 Ajax 选项卡控件的页面 其中一个选项卡中有一个 Web 控件 它是 Telerik RadGrid 其中编辑表单指向另一个 Web 控件 该编辑表单还包含 Ajax 选项卡 并且在其中一个选项卡上 还有另一个 Web 控件
  • Matlab 中的曲面图

    我正在尝试用对角矩阵绘制曲面 我正在尝试绘制的方程是 f x TDx x 是 2 x 1 向量 D 是 2 x 2 矩阵 这是到目前为止的内容 但我不断收到错误 x linspace 10 10 y linspace 10 10 X Y m
  • 如何将推文居中?

    Twitter 提供了嵌入推文的代码 例如我有 blockquote class twitter tweet p NoSQL space gradually becoming SlowSQL space p mdash Big Data B
  • 为什么我的 TreeSet 不添加第一个元素之外的任何内容?

    我有几个形式的数组 private static String patientNames John Lennon Paul McCartney George Harrison Ringo Starr 然后我制作一个像这样的 TreeSet
  • R knit:可以以编程方式修改块标签吗?

    我正在尝试使用 knit 生成一份报告 该报告对数据集的不同子集执行相同的分析集 该项目包含两个 Rmd 文件 第一个文件是设置工作区和文档的主文档 第二个文件仅包含执行分析并生成相关图形的块 我想做的是编织主文件 然后为每个数据子集调用第
  • Cin 对象返回值 C++ [重复]

    这个问题在这里已经有答案了 我想问一下cin的返回值是多少 我知道它是 ifstream 对象 并且当它在表达式中使用时 如if cin 实际上有一个函数被调用 我想知道它实际上是什么函数 cin fail 或 cin good 或 是if
  • SQL Server 2000 中的交叉表查询

    我希望以前有人尝试过这一点 并且在我进一步之前可以得到一些建议 我希望在 sql server 2000 中生成类似于交叉表查询的内容 我有一个类似于以下的表结构 Item Item Parameter Parameter id item
  • 在我的 iOS 应用程序中实施新的 Google 地图 SDK

    更新 我刚刚收到一封来自 Google 的有关新 Google 地图 iOS SDK 的电子邮件 看来一切都已经解决了 我已成功为我的应用程序创建新的 API 密钥 还没有测试过 但看起来是正确的 他们派我来this https devel
  • 我应该何时以及如何使用 ThreadLocal 变量?

    我什么时候应该使用ThreadLocal https docs oracle com javase 8 docs api java lang ThreadLocal html多变的 它是如何使用的 一种可能 也是常见 的用途是当您有一些非线
  • PHP cURL:获取重定向目标,而不跟随它

    curl getinfo 函数返回大量有关 HTTP 请求结果的元数据 但是 由于某种原因 它不包含我目前想要的信息 如果请求返回 HTTP 重定向代码 则该信息是目标 URL 我没有使用 CURLOPT FOLLOWLOCATION 因为
  • 在 React Native 中使用 mobx 进行状态存储时无法导航到不同的导航菜单

    我对 Mobx 有点陌生 一般来说 我的反应是原生的 我正在尝试使用 mobx 在导航堆栈中实现状态值更改 以便当单击登录按钮时 状态中的值会发生更改 并且导航值参数令牌会更新为 mobx 存储中的最新值 但这不起作用 我收到错误错误任何导