简体   繁体   English

找不到变量 setUserEmail

[英]Can't find variable setUserEmail

I'm linking my backend with my frontend in react native and I get this error Can't find-variable: setUserEmail when I go to type in an email into the TextInput .我将我的后端与我的前端以反应本机链接,我收到此错误Can't find-variable: setUserEmail when I go 输入 email 到TextInput I'm working on the login page and use a fetch API to log the user into the app.我正在登录页面上工作并使用获取 API 将用户登录到应用程序。 I followed a tutorial to the point but I'm getting this error each time I try to enter an email, I get a message say setUserEmail is declared but never used.我按照教程进行操作,但每次尝试输入 email 时都会出现此错误,我收到一条消息说setUserEmail已声明但从未使用过。 Any help would be greately appreciated任何帮助将不胜感激

import React, { Component, useState, createRef } from 'react';
import { StyleSheet, Text, TextInput, View, Dimensions, StatusBar, TouchableOpacity,Keyboard } from 'react-native';

export default function Login(){         
    const [userEmail, setUserEmail] = useState('');
    const [userPassword, setUserPassword] = useState('');
    const [loading, setLoading] = useState(false);

    const handleSubmitPress = () => {
        setLoading(true);
        let dataToSend = {userEmail: userEmail, password: userPassword};
        let formBody = [];
        for (let key in dataToSend) {
            let encodedKey = encodeURIComponent(key);
            let encodedValue = encodeURIComponent(dataToSend[key]);
            formBody.push(encodedKey + '=' + encodedValue);
        }
        formBody = formBody.join('&');

        fetch('http://localhost:3000/users/users', {
            method: "POST",
            headers: {
            Accept: "application/json",
            "Content-Type": "application/json",            
            "Cache-Control": "no-cache",
            Pragma: "no-cache",
            Expires: "0",
        },
            body: JSON.stringify({
            userEmail: userEmail,                 
            password: userPassword,                
            os: Platform.OS === "ios" ? "iOS" : "Android",
            }),
        })
        .then((response) => response.json())
        .then((responseJson) => {
        //Hide Loader
        setLoading(false);
        console.log(responseJson);
        // If server response message same as Data Matched
        if (responseJson.status === 'success') {
            AsyncStorage.setItem('user_id', responseJson.data.email);
            console.log(responseJson.data.email);
            navigation.replace('DrawerNavigationRoutes');
        } else {
            setErrortext(responseJson.msg);
            console.log('Please check your email id or password');
            }
        })
        .catch((error) => {
        //Hide Loader
        setLoading(false);
        console.error(error);
        });
    }

    return(
        <View style={style.container}>

            <View style={style.parent}>
                <Text style={style.title}>Login</Text>
                <Text style={style.heading}>Please Sign in to continue</Text>
            </View>

            <View style={style.root}>
                <TextInput name='txtEmail' placeholder='someone@something.com' style={style.email} onChangeText={(UserEmail) => setUserEmail(UserEmail)}/>
                <TextInput type='password' name='txtPassword' placeholder='Password' secureTextEntry={true} style={style.password} onChangeText={(UserPassword) => setUserPassword(UserPassword)}/>                                                    
                <Text style={style.forgotpassword}>Forgot Password?</Text>

                <TouchableOpacity 
                    title="Login"
                    style={style.login}
                    onPress={handleSubmitPress()}>

                    <Text style={style.login_caption}>Login </Text>
                </TouchableOpacity>     

            </View>

                
            <StatusBar hidden />
        </View>
    );
    
}

const style =  StyleSheet.create({
    container:{
        width: Dimensions.get('window').width,
        height: Dimensions.get('window').height,          
    },
    forgotpassword:{
        textAlign: 'right',
        marginTop: 10,
    },
    login:{
        width: 150,
        height: 45,
        backgroundColor: '#FFB900',     
        position: 'absolute',
        right: 0,  
        marginLeft: 25,
        marginRight: 15,         
        marginTop: 150,
        borderRadius: 25,        
    },
    login_caption:{
        color: '#fff',
        textAlign: 'left',
        paddingLeft: 15,
        justifyContent: 'center',        
        paddingTop: 12,        
    },
    parent:{
        marginTop: 85,
    },
    title:{
        fontSize: 36,
        fontWeight: "900",
        paddingLeft: 25,
    },
    heading:{
        color: '#C0C0C0',
        paddingLeft: 25,
    },
    root:{
        width: 250,
        height: 350,                     
        marginTop: 85,
        alignSelf: 'center',
    },
    email:{        
        width: 275,
        height:38,
        borderColor: "#111",
        borderWidth: 1,
        fontSize: 16,
        paddingLeft:10,
        justifyContent: 'center',
        borderRadius: 15, 
        alignSelf: 'center',
    },
    password:{
        width: 275,
        height:38,
        borderColor: "#111",
        alignSelf: 'center',
        borderWidth: 1,
        fontSize: 16,
        paddingLeft:10,
        justifyContent: 'center',   
        marginTop: 15,
        borderRadius: 15,    
    }
});

UPDATED WITH CHANGES

With a little bit of cleaning, that what I ended up with:通过一点清洁,我最终得到了:

import AsyncStorage from "@react-native-community/async-storage";
import React, { useState } from "react";
import { Dimensions, Platform, StatusBar, StyleSheet, Text, TextInput, TouchableOpacity, View } from "react-native";

const Login = () => {
  const [userEmail, setUserEmail] = useState("");
  const [userPassword, setUserPassword] = useState("");
  const [errorText, setErrorText] = useState("");
  const [loading, setLoading] = useState(false);

  const handleSubmitPress = () => {
    setLoading(true);
    const dataToSend = { userEmail: userEmail, password: userPassword };
    let formBody = [];
    for (const key in dataToSend) {
      const encodedKey = encodeURIComponent(key);
      const encodedValue = encodeURIComponent(dataToSend[key]);
      formBody.push(encodedKey + "=" + encodedValue);
    }
    formBody = formBody.join("&");

    fetch("http://localhost:3000/users/users", {
      method: "POST",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
        "Cache-Control": "no-cache",
        Pragma: "no-cache",
        Expires: "0",
      },
      body: JSON.stringify({
        userEmail: userEmail,
        password: userPassword,
        os: Platform.OS === "ios" ? "iOS" : "Android",
      }),
    })
      .then((response) => response.json())
      .then((responseJson) => {
        //Hide Loader
        setLoading(false);
        console.log(responseJson);
        // If server response message same as Data Matched
        if (responseJson.status === "success") {
          AsyncStorage.setItem("user_id", responseJson.data.email);
          console.log(responseJson.data.email);
          // navigation.replace('DrawerNavigationRoutes');
        } else {
          setErrorText(responseJson.msg);
          console.log("Please check your email id or password");
        }
      })
      .catch((error) => {
        //Hide Loader
        setLoading(false);
        console.error(error);
      });
  };

  return (
    <View style={styles.container}>
      <View style={styles.parent}>
        <Text style={styles.title}>Login</Text>
        <Text style={styles.heading}>Please Sign in to continue</Text>
      </View>

      <View style={styles.root}>
        <TextInput
          name="txtEmail"
          placeholder="someone@something.com"
          style={styles.email}
          onChangeText={(UserEmail) => setUserEmail(UserEmail)}
        />
        <TextInput
          type="password"
          name="txtPassword"
          placeholder="Password"
          secureTextEntry={true}
          style={styles.password}
          onChangeText={(UserPassword) => setUserPassword(UserPassword)}
        />
        <Text style={styles.forgotpassword}>Forgot Password?</Text>

        <TouchableOpacity title="Login" style={styles.login} onPress={handleSubmitPress}>
          <Text style={styles.login_caption}>Login </Text>
        </TouchableOpacity>
      </View>
      <StatusBar hidden />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    height: Dimensions.get("window").height,
    width: Dimensions.get("window").width,
  },
  email: {
    alignSelf: "center",
    borderColor: "#111",
    borderRadius: 15,
    borderWidth: 1,
    fontSize: 16,
    height: 38,
    justifyContent: "center",
    paddingLeft: 10,
    width: 275,
  },
  forgotpassword: {
    marginTop: 10,
    textAlign: "right",
  },
  heading: {
    color: "#C0C0C0",
    paddingLeft: 25,
  },
  login: {
    backgroundColor: "#FFB900",
    borderRadius: 25,
    height: 45,
    marginLeft: 25,
    marginRight: 15,
    marginTop: 150,
    position: "absolute",
    right: 0,
    width: 150,
  },
  login_caption: {
    color: "#fff",
    justifyContent: "center",
    paddingLeft: 15,
    paddingTop: 12,
    textAlign: "left",
  },
  parent: {
    marginTop: 85,
  },
  password: {
    alignSelf: "center",
    borderColor: "#111",
    borderRadius: 15,
    borderWidth: 1,
    fontSize: 16,
    height: 38,
    justifyContent: "center",
    marginTop: 15,
    paddingLeft: 10,
    width: 275,
  },
  root: {
    alignSelf: "center",
    height: 350,
    marginTop: 85,
    width: 250,
  },
  title: {
    fontSize: 36,
    fontWeight: "900",
    paddingLeft: 25,
  },
});

export default Login;

There were few mistakes in your code,您的代码中几乎没有错误,

  • you used setErrorText without declaring it.您使用setErrorText没有声明它。
  • this line <TouchableOpacity title="Login" style={styles.login} onPress={handleSubmitPress()}> was not good, maybe it was the cause of infinite rendering.这行<TouchableOpacity title="Login" style={styles.login} onPress={handleSubmitPress()}>不好,可能是无限渲染的原因。

I solved all those errors very easily by using some extension in my IDE to clean code automatically like prettier and ESLint , and I used typescript.我通过在我的 IDE 中使用一些扩展来像prettierESLint一样自动清理代码,非常轻松地解决了所有这些错误,我使用了 typescript。 I really suggests that you do the same.真的建议你也这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM