找不到变量 setUserEmail

Posted

技术标签:

【中文标题】找不到变量 setUserEmail【英文标题】:Can't find variable setUserEmail 【发布时间】:2022-01-19 10:17:14 【问题描述】:

我在 react native 中将我的后端与我的前端链接起来,当我在TextInput 中输入电子邮件时,我收到了这个错误Can't find-variable: setUserEmail。我正在处理登录页面并使用 fetch API 将用户登录到应用程序。我按照教程进行操作,但每次尝试输入电子邮件时都会收到此错误,我收到一条消息说setUserEmail 已声明但从未使用过。任何帮助将不胜感激

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

【问题讨论】:

我认为setUserEmail不在render()的范围内。您在fetchData() 中定义了setUserEmail,并且您在render() 中使用它。尝试在组件的开头定义状态。 我该怎么做 你能发布整个文件而不是上面的 sn-p 吗?由于 cmets 的字符限制,我将检查并尝试将其发布在答案部分。 我同意@PR7,也认为你没有使用Function Component but rather Class Component。问题是你不能在功能组件中使用hooks。 所以使用更新的代码我得到了太多的重新渲染 【参考方案1】:

稍微打扫一下,我就得到了:

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;

您的代码中几乎没有错误,

你使用了setErrorText 却没有声明它。 &lt;TouchableOpacity title="Login" style=styles.login onPress=handleSubmitPress()&gt;这行不好,可能是无限渲染的原因。

我通过在我的 IDE 中使用一些扩展来自动清理代码,例如 prettierESLint,非常轻松地解决了所有这些错误,并且我使用了 typescript。我真的建议你也这样做。

【讨论】:

我在安装异步存储时遇到一个错误,说在项目中找不到它 @PureWare-LegendsOfGaming,然后删除这行import AsyncStorage from "@react-native-community/async-storage";。我虽然这是你用的。

以上是关于找不到变量 setUserEmail的主要内容,如果未能解决你的问题,请参考以下文章

错误找不到符号变量 id

Cordova 找不到变量:NativeStorage

找不到变量:Safari 中的 MediaRecorder

Cordova 找不到 ANDROID_HOME 环境变量

MATLAB7.0安装后,启动弹出找不到指定的模块

找不到变量 atob