类型错误:无法读取 undefine

时间:2021-07-26 19:57:03

标签: javascript node.js react-native

大家晚上好!!

我正在尝试单击“登录或注册按钮”,但收到以下错误:“类型错误:无法读取未定义的属性‘导航’”

我试图在项目中做一些小的改变,但没有快乐:(

TypeError: Cannot read property 'navigate' of undefined
onPress
C:/Users/André Vieira/DoneWithit/app/screens/WelcomeScreen.js:21
  18 | <View style={styles.buttonsContainer}>
  19 |   <Button
  20 |     title="Login"
> 21 |     onPress={() => navigation.navigate(routes.LOGIN)}
     | ^  22 |   />
  23 |   <Button
  24 |     title="Register"
View compiled

这是我的登录界面

import React, { useState } from "react";
import { StyleSheet, Image } from "react-native";
import * as Yup from "yup";

import Screen from "../components/Screen";
import {
  ErrorMessage,
  Form,
  FormField,
  SubmitButton,
} from "../components/forms";
import authApi from "../api/auth";
import useAuth from "../auth/useAuth";

const validationSchema = Yup.object().shape({
  email: Yup.string().required().email().label("Email"),
  password: Yup.string().required().min(4).label("Password"),
});

function LoginScreen(props) {
  const auth = useAuth();
  const [loginFailed, setLoginFailed] = useState(false);

  const handleSubmit = async ({ email, password }) => {
    const result = await authApi.login(email, password);
    if (!result.ok) return setLoginFailed(true);
    setLoginFailed(false);
    auth.logIn(result.data);
  };

  return (
    <Screen style={styles.container}>
      <Image style={styles.logo} source={require("../assets/logo-red.png")} />

      <Form
        initialValues={{ email: "", password: "" }}
        onSubmit={handleSubmit}
        validationSchema={validationSchema}
      >
        <ErrorMessage
          error="Invalid email and/or password."
          visible={loginFailed}
        />
        <FormField
          autoCapitalize="none"
          autoCorrect={false}
          icon="email"
          keyboardType="email-address"
          name="email"
          placeholder="Email"
          textContentType="emailAddress"
        />
        <FormField
          autoCapitalize="none"
          autoCorrect={false}
          icon="lock"
          name="password"
          placeholder="Password"
          secureTextEntry
          textContentType="password"
        />
        <SubmitButton title="Login" />
      </Form>
    </Screen>
  );
}

const styles = StyleSheet.create({
  container: {
    padding: 10,
  },
  logo: {
    width: 80,
    height: 80,
    alignSelf: "center",
    marginTop: 50,
    marginBottom: 20,
  },
});

export default loginscreen;

也许很简单,但我想不通。

有人帮忙吗?谢谢

我的欢迎屏幕

import React from "react";
import { ImageBackground, StyleSheet, View, Image, Text } from "react-native";

import Button from "../components/Button";
import routes from "../navigation/routes";

function WelcomeScreen({ navigation }) {
  return (
    <ImageBackground
      blurRadius={10}
      style={styles.background}
      source={require("../assets/background.jpg")}
    >
      <View style={styles.logoContainer}>
        <Image style={styles.logo} source={require("../assets/logo-red.png")} />
        <Text style={styles.tagline}>Sell What You Don't Need</Text>
      </View>
      <View style={styles.buttonsContainer}>
        <Button
          title="Login"
          onPress={() => navigation.navigate(routes.LOGIN)}
        />
        <Button
          title="Register"
          color="secondary"
          onPress={() => navigation.navigate(routes.REGISTER)}
        />
      </View>
    </ImageBackground>
  );
}

const styles = StyleSheet.create({
  background: {
    flex: 1,
    justifyContent: "flex-end",
    alignItems: "center",
  },
  buttonsContainer: {
    padding: 20,
    width: "100%",
  },
  logo: {
    width: 100,
    height: 100,
  },
  logoContainer: {
    position: "absolute",
    top: 70,
    alignItems: "center",
  },
  tagline: {
    fontSize: 25,
    fontWeight: "600",
    paddingVertical: 20,
  },
});

export default WelcomeScreen;

来自控制台

Uncaught TypeError: Cannot read property 'navigate' of undefined
    at onPress (WelcomeScreen.js:21)
    at onClick (PressResponder.js:333)
    at HTMLUnknownElement.callCallback (react-dom.development.js:188)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:237)
    at invokeGuardedCallback (react-dom.development.js:292)
    at invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:306)
    at executeDispatch (react-dom.development.js:389)
    at executeDispatchesInOrder (react-dom.development.js:414)
    at executeDispatchesAndRelease (react-dom.development.js:3278)
    at executeDispatchesAndReleaseTopLevel (react-dom.development.js:3287)
    at forEachAccumulated (react-dom.development.js:3259)
    at runEventsInBatch (react-dom.development.js:3304)
    at runExtractedPluginEventsInBatch (react-dom.development.js:3514)
    at handleTopLevel (react-dom.development.js:3558)
    at batchedEventUpdates$1 (react-dom.development.js:21871)
    at batchedEventUpdates (react-dom.development.js:795)
    at dispatchEventForLegacyPluginEventSystem (react-dom.development.js:3568)
    at attemptToDispatchEvent (react-dom.development.js:4267)
    at dispatchEvent (react-dom.development.js:4189)
    at unstable_runWithPriority (scheduler.development.js:653)
    at runWithPriority$1 (react-dom.development.js:11039)
    at discreteUpdates$1 (react-dom.development.js:21887)
    at discreteUpdates (react-dom.development.js:806)
    at dispatchDiscreteEvent (react-dom.development.js:4168)

3 个答案:

答案 0 :(得分:1)

似乎WelcomeScreen 不在导航器内部,向下传递导航作为道具。如果您使用的是 react-navigation 5.x,则可以使用钩子:

import React from "react";
import { ImageBackground, StyleSheet, View, Image, Text } from "react-native";
import { useNavigation } from '@react-navigation/native';

import Button from "../components/Button";
import routes from "../navigation/routes";

function WelcomeScreen() {
  const navigation = useNavigation();

  return (
    <ImageBackground
      blurRadius={10}
      style={styles.background}
      source={require("../assets/background.jpg")}
    >
      <View style={styles.logoContainer}>
        <Image style={styles.logo} source={require("../assets/logo-red.png")} />
        <Text style={styles.tagline}>Sell What You Don't Need</Text>
      </View>
      <View style={styles.buttonsContainer}>
        <Button
          title="Login"
          onPress={() => navigation.navigate(routes.LOGIN)}
        />
        <Button
          title="Register"
          color="secondary"
          onPress={() => navigation.navigate(routes.REGISTER)}
        />
      </View>
    </ImageBackground>
  );
}

const styles = StyleSheet.create({
  background: {
    flex: 1,
    justifyContent: "flex-end",
    alignItems: "center",
  },
  buttonsContainer: {
    padding: 20,
    width: "100%",
  },
  logo: {
    width: 100,
    height: 100,
  },
  logoContainer: {
    position: "absolute",
    top: 70,
    alignItems: "center",
  },
  tagline: {
    fontSize: 25,
    fontWeight: "600",
    paddingVertical: 20,
  },
});

export default WelcomeScreen;

https://reactnavigation.org/docs/use-navigation/

答案 1 :(得分:1)

JS 在以下情况下返回 undefined - 1) 您试图达到的值不存在。 2)您使用的值不存在 3) 函数没有返回任何东西。 4)当你使用纯代码时,代码中没有任何功能。 当一个值不存在时? - 当它实际上不存在或您没有收到它以便您可以使用它时。

在你的情况下 - 您的 navigation 位于一个对象内(welcomeScreen(parameter) 的参数。您需要先到达该 object。然后您就可以使用函数 navigate

也可能是因为 routes 未正确导入。

答案 2 :(得分:0)

在 Pernifeous 解决方案之后,我开始得到这个:

Error: Couldn't find a navigation object. Is your component inside a screen in a navigator?
▶ 21 stack frames were collapsed.
registerRootComponent
C:/Users/src/launch/registerRootComponent.tsx:14
  11 |   AppRegistry.registerComponent('main', () => withExpoRoot(component));
  12 |   if (Platform.OS === 'web') {
  13 |     const rootTag = document.getElementById('root') ?? document.getElementById('main');
> 14 |     AppRegistry.runApplication('main', { rootTag });
  15 |   }
  16 | }
  17 | 

我的路由配置:

export default Object.freeze({
  LISTING_DETAILS: "ListingDetails",
  LISTING_EDIT: "ListingEdit",
  LOGIN: "Login",
  MESSAGES: "Messages",
  REGISTER: "Register",
});