React Native登录按钮无响应,无法触发登录函数及请求的问题求助
React Native登录按钮无响应,无法触发登录函数及请求的问题求助
各位好,我现在碰到一个头疼的问题:React Native里的登录按钮完全没反应,既不触发fetch请求,也没有任何提示弹窗。
具体情况是:点击Login按钮后,我本以为会给后端发POST请求,拿到响应后弹出“Success”或者“Error”的提示,但实际啥都没发生——没有弹窗,Login函数里的console.log也没输出,后端服务器根本收不到请求。
我的环境配置
- 后端是Windows电脑上运行的简单Express服务,端口3000
- 前端用Expo在我的手机上运行,手机和电脑连的同一个Wi-Fi网络
- fetch请求里用的是电脑的本地IP:
192.168.1.46
我已经尝试过的排查步骤
- 确认手机能访问后端:用手机浏览器打开
http://192.168.1.46:3000是能正常访问的 - 在Login函数里加了
console.log语句,但完全没输出,说明函数根本没执行 - 检查了TouchableOpacity的onPress绑定,确实是
onPress={Login} - 查看了控制台,没有任何报错信息
前端React Native代码片段
import React, { useState } from "react"; import {View, Text, StyleSheet, TextInput, TouchableOpacity, Alert} from 'react-native' export default function Main() { const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const Login = async () => { try { console.log("Sending:", email, password); const response = await fetch("http://192.168.1.46:3000/login", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ email, password }) }); const data = await response.json(); if (response.ok) { Alert.alert("Success", "Logged in!"); console.log("Server Response:", data); } else { Alert.alert("Error", data.message || "Login failed"); } } catch (error) { console.error("Login Error:", error); Alert.alert("Error", "Something went wrong"); } }; return ( <View style={style.container}> <View style={style.box}> <Text style={style.label}>Email</Text> <TextInput style={style.input} value={email} onChangeText={(text) => setEmail(text)} placeholder="Enter your email" /> <Text style={style.label}>Password</Text> <TextInput style={style.input} value={password} onChangeText={(text) => setPassword(text)} placeholder="Enter your pass" secureTextEntry={true} /> <TouchableOpacity onPress={Login}> <Text>Login</Text> </TouchableOpacity> </View> </View> ) } const style = StyleSheet.create({ container: { flex: 1, backgroundColor: '#b343fc', justifyContent: 'center', alignItems: 'center', padding: 20 }, box: { backgroundColor: "#", borderRadius: 12, padding: 50, width: "100%", maxWidth: 350, shadowColor: "#000", shadowOpacity: 2, shadowOffset: { width: 0, height: 2 }, shadowRadius: 6, elevation: 4, // Android shadow }, label: { fontSize: 16, fontWeight: "600", marginBottom: 5, fontFamily: "monospace" }, input: { backgroundColor: "#f2f2f2", borderRadius: 8, padding: 10, marginBottom: 15, fontFamily: "monospace", } })
后端Express代码片段
const express = require('express') const app = express() const port = 3000 app.use(express.json()) app.post('/login', (req, res) => { const {email, password} = req.body; console.log('Login succesful: ', email, password) res.json({ message: `Logged in as ${email}` }); }); app.listen(port, () => { console.log(`Server running at http://localhost:${port}`); });
内容来源于stack exchange
相关产品推荐
相关产品推荐

